Export ASP.NET DataGrid to Excel

Export to Excel is one of the most common functionalities required in ASP.Net pages. Users can download the data from the datagrid into an Excel spreadsheet for offline verification and/or computation. This article includes the source code for such functionality.

How it works

This main functionality to Export a datagrid from an ASP.Net Web Form to an Excel format is actually very simple. There are several solutions for this implementation and in this example we will convert the datagrid to excel format by manipulating the MIME type (media type or Content Type) of the Response. The RenderControl method available in the .Net Framework provides the server control content to an HtmlTextWriter which is subsequently written out to the Response Stream.

  1. private void Button1_Click(object sender, System.EventArgs e)  
  2. {  
  3.     //export to excel  
  4.     Response.Clear();  
  5.     Response.Buffer = true;  
  6.     Response.ContentType = "application/vnd.ms-excel";  
  7.     Response.Charset = "";  
  8.     this.EnableViewState = false;  
  9.     System.IO.StringWriter oStringWriter = new System.IO.StringWriter();  
  10.     System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);  
  11.     this.ClearControls(dg);  
  12.     dg.RenderControl(oHtmlTextWriter);  
  13.     Response.Write(oStringWriter.ToString());  
  14.     Response.End();  
  15. }  
Code Listing: Output the contents of the datagrid to Excel spreadsheet

And just one more detail

There's just one thing to take care of. A run-time error occurs if the DataGrid contains any controls other than the LiteralControl. This means that enabling Sorting, Paging or adding Template Columns or Button columns to the datagrid can cause an error. There are several approaches to work around this limitation. We will remove all the non-Literal controls in the DataGrid and replace the controls with a text representation, where possible. To do so, we will make use of Reflection. instead of querying each type of control and working out a replacement.

For all controls that have a SelectedItem property, we replace the control with the literal value of the SelectedItem property of the control. This covers most lists. For all controls that have a Text property, we replace the control with the literal value of the Text property of the control. This covers TextBox, Buttons, Button Columns, TemplateColumns. We make an exception only for TableCell controls. This takes care of most of the cases and you can add more checks and balances as required. The only drawback for this generalized formula is the order of the controls within a single cell could get changed.

  1. private void ClearControls(Control control)  
  2. {  
  3.     for (int i = control.Controls.Count - 1; i >= 0; i--)  
  4.     {  
  5.         ClearControls(control.Controls[i]);  
  6.     }  
  7.     if (!(control is TableCell))  
  8.     {  
  9.         if (control.GetType().GetProperty("SelectedItem") != null)  
  10.         {  
  11.             LiteralControl literal = new LiteralControl();  
  12.             control.Parent.Controls.Add(literal);  
  13.             try  
  14.             {  
  15.                 literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);  
  16.             }  
  17.             catch  
  18.             {  
  19.             }  
  20.             control.Parent.Controls.Remove(control);  
  21.         }  
  22.         else  
  23.         if (control.GetType().GetProperty("Text") != null)  
  24.         {  
  25.             LiteralControl literal = new LiteralControl();  
  26.             control.Parent.Controls.Add(literal);  
  27.             literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);  
  28.             control.Parent.Controls.Remove(control);  
  29.         }  
  30.     }  
  31.     return;  
  32. }  
Code Listing: Output the contents of the datagrid to Excel spreadsheet

In our sample web form, we connect to the Sample Pubs SQL Server database and display the data from the Employees table. The sample datagrid uses paging and a dummy Edit Column.

Complete Code Listing

  1. <%@ Page language = "C#" Debug="true" %>  
  2. <%@ Import Namespace = "System.Drawing" %>  
  3. <%@ Import Namespace = "System.Data" %>  
  4. <%@ Import Namespace = "System.Data.SqlClient" %>  
  5.   
  6. < script Language="C#" runat="server">  
  7. private void Button1_Click(object sender, System.EventArgs e)  
  8. {  
  9.     //export to excel  
  10.     Response.Clear();  
  11.     Response.Buffer = true;  
  12.     Response.ContentType = "application/vnd.ms-excel";  
  13.     Response.Charset = "";  
  14.     this.EnableViewState = false;  
  15.     System.IO.StringWriter oStringWriter = new System.IO.StringWriter();  
  16.     System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);  
  17.     this.ClearControls(dg);  
  18.     dg.RenderControl(oHtmlTextWriter);  
  19.     Response.Write(oStringWriter.ToString());  
  20.     Response.End();  
  21. }  
  22. private void Page_Load(object sender, System.EventArgs e)  
  23. {  
  24.     if (!IsPostBack)  
  25.     {  
  26.         SqlConnection conn = new SqlConnection("data source=(local);initial catalog=Northwind;Pwd=p@ssw0rd;User  
  27.         ID = sa");  
  28.         SqlCommand cmd = new SqlCommand("Select LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate,  
  29.         Address, City, Region, PostalCode, Country from Employees", conn);  
  30.         SqlDataAdapter da = new SqlDataAdapter(cmd);  
  31.         DataSet ds = new DataSet();  
  32.         da.Fill(ds);  
  33.         dg.DataSource = ds.Tables[0];  
  34.         dg.DataBind();  
  35.     }  
  36. }  
  37. private void ClearControls(Control control)  
  38. {  
  39.     for (int i = control.Controls.Count - 1; i >= 0; i--)  
  40.     {  
  41.         ClearControls(control.Controls[i]);  
  42.     }  
  43.     if (!(control is TableCell))  
  44.     {  
  45.         if (control.GetType().GetProperty("SelectedItem") != null)  
  46.         {  
  47.             LiteralControl literal = new LiteralControl();  
  48.             control.Parent.Controls.Add(literal);  
  49.             try  
  50.             {  
  51.                 literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValuecontrol,null);  
  52.             }  
  53.             catch  
  54.             {  
  55.             }  
  56.             control.Parent.Controls.Remove(control);  
  57.         }  
  58.         else  
  59.         if (control.GetType().GetProperty("Text") != null)  
  60.         {  
  61.             LiteralControl literal = new LiteralControl();  
  62.             control.Parent.Controls.Add(literal);  
  63.             literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);  
  64.             control.Parent.Controls.Remove(control);  
  65.         }  
  66.     }  
  67.     return;  
  68. }  
  69. </script>  
  70. <html>  
  71. <body leftmargin = "0" topmargin="0" marginwidth="0" marginheight="0">  
  72. <form id = "frm" runat="server">  
  73. <asp:Button id = "Button1" runat="server" Text="Export to Excel"  
  74. OnClick="Button1_Click"></asp:Button><BR>  
  75. <asp:Datagrid id = "dg" runat="server" AutoGenerateColumns="True"  
  76. AllowSorting="true" AllowPaging="true"CellPadding="3" PageSize=3>  
  77. <columns>  
  78. <asp:TemplateColumn>  
  79. <ItemTemplate>  
  80. <asp:LinkButton runat = "server" CommandName="Edit"CausesValidation="false" ID="btnView"Text="Edit"/>  
  81. </ItemTemplate>  
  82. </asp:TemplateColumn>  
  83. </columns>  
  84. </asp:datagrid>  
  85. <BR>  
  86. </form>  
  87. </body>  
  88. </html>  
Note that you will need to have Excel 97 or later installed on the client. You can also add extra code for formatting the excel output.

 

NOTE: This article is purely for educational purpose. This article should not be construed as a best practices white paper. This article is entirely original, unless specified. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof.


Similar Articles