Converting a grid to excel document in vb.net

A little script to convert a gridview to an excel document. This always came handy when someone needed to create a report right out of gridview ... You can call the function like this ...
ExportGridToExcel(grd, "report.xls")
 
---Copy the code below and paste it in your script
 
Public Sub ExportGridToExcel(ByRef grdGridView As GridView, ByVal fileName As String)
 
Response.Clear()
 
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", fileName))
 
Response.Charset = ""
 
Response.ContentType = "application/vnd.xls"
 
Dim strWriter As New StringWriter()
 
Dim HtmlWriter As New HtmlTextWriter(strWriter)
 
grdGridView.RenderControl(HtmlWriter)
 
Response.Write(strWriter.ToString)
 
Response.End()
 
End Sub
 
Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
 
'You will need this part else you will get error like "runat=server needs to be before ....."
 
End Sub
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*