This approach is render the web control directly to excel:
First thing to do is to override the following verification as follows:
Next is to render the control as follows:
' required to prevent error of control not running within "form runat=server" tags
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)
'###this removes the no forms error by overriding the error
'Export the datagrid to excel
Private Sub btnExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExcel.Click
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim tw As New System.IO.StringWriter
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
I have left out the aspx codes and the rest of the codes and assume that those portion are already taken care of.
Notice the following:
- response.clear is done to clear off anything left over in the response buffer.
- We pass in the data grid to VerifyRenderingInServerForm
- A string writer is used to render the control.
- We don't have to bother about hiding any other controls. Only the datagrid will be rendered to Excel.
- Since the datagrid is already bound and contains data, the program need not go back to the database to process the data again.
- This approach only works with asp.net.
- You will not see other information other than the datagrid.
Links to earlier articles found below: