I just found a neat way to output the results of an ASP.NET DataGrid to Excel. Just put the following code in a button_click event handler, and when a user clicks the button, it will output the DataGrid, including formatting, to a new Excel window, leaving the browser window undisturbed. Of course this assumes your users have Excel.
' Set the content type to Excel
Response.ContentType = "application/vnd.ms-excel"
'Turn off the view state
Me.EnableViewState = False
'Remove the charset from the Content-Type header
Response.Charset = String.Empty
Dim myTextWriter As New System.IO.StringWriter()
Dim myHtmlTextWriter As New System.Web.UI.HtmlTextWriter(myTextWriter)
'Get the HTML for the control
myDataGrid.RenderControl(myHtmlTextWriter)
'Write the HTML to the browser
Response.Write(myTextWriter.ToString())
'End the response
Response.End()
Update: Added the Response.ContentType line which I had inadvertently forgotten.
Update 2: Brendan Tompkins has graciously offered 3 XSLT files to transform a DataGrid's XML into Excel, comma-delimited, and tab-delimited files. Thanks Brendan!
Posted
02-12-2004 7:50 PM
by
Darrell Norton