Hello,
I found the code to export contents of a gridview to excel on a webpage:
Sub doExcel(Source as Object, E as EventArgs)
If Grid1.Rows.Count.ToString + 1 < 65536 Then
Grid1.AllowPaging = "False"
Grid1.DataBind()
Dim tw As New StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim frm As HtmlForm = New HtmlForm()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment;filename=Test.xls")
Response.AddHeader("content-disposition", "attachment;filename=" & txtFile.text & ".xls")
Response.Charset = ""
EnableViewState = False
Controls.Add(frm)
frm.Controls.Add(Grid1)
frm.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
Grid1.AllowPaging = "True"
Grid1.DataBind()
Else
LblError.Text = "Too many rows - Export to Excel not possible"
End If
End Sub
this code works but the problem is I dont understand how it works.
I dont understand why we need to create a new form and add controls to it, how the data gets copied from the gridview to the excel file etc..
Could someone explain this code to me please?
Thank you,
Burak
I found the code to export contents of a gridview to excel on a webpage:
Sub doExcel(Source as Object, E as EventArgs)
If Grid1.Rows.Count.ToString + 1 < 65536 Then
Grid1.AllowPaging = "False"
Grid1.DataBind()
Dim tw As New StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim frm As HtmlForm = New HtmlForm()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment;filename=Test.xls")
Response.AddHeader("content-disposition", "attachment;filename=" & txtFile.text & ".xls")
Response.Charset = ""
EnableViewState = False
Controls.Add(frm)
frm.Controls.Add(Grid1)
frm.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
Grid1.AllowPaging = "True"
Grid1.DataBind()
Else
LblError.Text = "Too many rows - Export to Excel not possible"
End If
End Sub
this code works but the problem is I dont understand how it works.
I dont understand why we need to create a new form and add controls to it, how the data gets copied from the gridview to the excel file etc..
Could someone explain this code to me please?
Thank you,
Burak