Display an ASP.NET DataGrid in Microsoft Excel
I was putting the finishing touches on a web application tonight when I discovered something really cool...
I've got a form where a user can select a whole slew of parameters to build a dynamic query and, once the results have been fetched I needed to render them as either:
- A plain, sortable, pageable DataGrid
- Rendered in a dynamically generated GUI
- Opened in a Microsoft Excel worksheet
I had already done the plain grid and the dynamic UI stuff - which, in itself was pretty cool - and tonight set about the task of doing the Excel part. The first place that I went to was the ASP.NET Support Center. This is an incredible resource and, if you haven't already done so, I'd suggest that you spend some time scouring through the "How To's" on that site. Anyways, I plugged the term: "Excel" into the "Search (KB) ASP.NET" form and submitted. I slid my eyes down the page about 10 items until they landed upon: "HOW TO: Export Data in a DataGrid on an ASP . NET WebForm to Microsoft Excel"... VOILA! Perfection. This was my resultant code to render the Excel Worksheet:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load BindGrid() RenderGrid() End Sub Private Sub BindGrid() Dim dtResults As DataTable = CType(Session("DynamicFormResults"), DataTable) If Not dtResults Is Nothing Then DataGrid1.DataSource = dtResults.DefaultView DataGrid1.DataBind() End If End Sub Private Sub RenderGrid() Response.ContentType = "application/vnd.ms-excel" ' Remove the charset from the Content-Type header. Response.Charset = "" ' Turn off the view state. Me.EnableViewState = False Dim tw As New System.IO.StringWriter Dim hw As New System.Web.UI.HtmlTextWriter(tw) ' Get the HTML for the control. DataGrid1.RenderControl(hw) ' Write the HTML back to the browser. Response.Write(tw.ToString()) ' End the response. Response.End() End Sub