Tips and tricks for .NET using ASP and VB code.

Send a GridView to Excel when a button is clicked.

Add EnableEventValidation="false" to <%@ Page %> tag.
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Response.Clear()
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls")
Response.Charset = ""
' If you want the option to open the Excel file without saving than
' comment out the line below
' Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls"
Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
GridView1.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.End()
End Sub

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
'Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
'This is required in order to send data to Excel.
End Sub

No comments:

Post a Comment

Search This Blog