Friday, October 19, 2007

A Simple Solution for Export ASP .NET Data Grid to Excel

This sample demonstrates an easy way to export DataGrid into an Excel file. Most of the web controls have a RenderControl method which will write an html text stream. All have to do is declare the response object, call RenderControl method and output the “rendering”. Quite simple!

Here is the code for the Export method:

Public Shared Sub ExportToExcel(ByVal dg As DataGrid, ByVal lblTitle As Label)
Try
If dg.Items.Count > 0 Then
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" & lblTitle.Text & ".xls")

'Remove the charset from the Content-Type header
HttpContext.Current.Response.Charset = ""

Dim lbl As New System.Web.UI.WebControls.Label
lbl.Text = "<>"

'Turn off the view state
lbl.EnableViewState = False
dg.EnableViewState = False
Dim tw As New System.IO.StringWriter
Dim hw As New System.Web.UI.HtmlTextWriter(tw)

'Get the HTML for the control
lblTitle.EnableViewState = False
lblTitle.RenderControl(hw)
lbl.RenderControl(hw)
lbl.RenderControl(hw)
dg.RenderControl(hw)

'Write the HTML back to the browser
HttpContext.Current.Response.Write(tw.ToString())

'End the response
HttpContext.Current.Response.End()
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub

This is really a simple solution. Hope it works out for you.

0 comments:

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
Sign up for PayPal and start accepting credit card payments instantly. http://www.emailcashpro.com
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template