Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » WebForms Controls » Export ASP.NET DataGrid to Excel

Export ASP.NET DataGrid to Excel

Export to Excel is one of the most common functionality required in ASP.NET pages. Users can download the data from the DataGrid into an Excel spreadsheet for offline verification and/or computation.

Author Rank :
Page Views : 321696
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Export to Excel is one of the most common functionality 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.

private void Button1_Click(object sender, System.EventArgs e)
{
//export to excel
Response.Clear();
Response.Buffer=
true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter =
new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter =
new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(dg);
dg.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}

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 Columnns or Button columns to the datagrid can cause an error. There are several approaches to workaround 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 generalised formula is the order of the controls within a single cell could get changed.

private void ClearControls(Control control)
{
for (int i=control.Controls.Count -1; i>=0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal =
new LiteralControl();
control.Parent.Controls.Add(literal);
try
{literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control,null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else
if
(control.GetType().GetProperty("Text") != null)
{
LiteralControl literal =
new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (
string)control.GetType().GetProperty("Text").GetValue(control,null);
control.Parent.Controls.Remove(control);
}
}
return;
}

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

<%@ Page language="C#" Debug="true" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script Language="C#" runat="server">
private void Button1_Click(object sender, System.EventArgs e)
{
//export to excel
Response.Clear();
Response.Buffer=
true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter =
new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter =
new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(dg);
dg.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
SqlConnection conn =
new SqlConnection ("data source=(local);initial catalog=Northwind;Pwd=p@ssw0rd;User
ID=sa");
SqlCommand cmd =
new SqlCommand ("Select LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate,
Address, City, Region, PostalCode, Country from Employees", conn);
SqlDataAdapter da =
new SqlDataAdapter(cmd);
DataSet ds =
new DataSet();
da.Fill(ds);
dg.DataSource = ds.Tables[0];
dg.DataBind();
}
}
private void ClearControls(Control control)
{
for (int i=control.Controls.Count -1; i>=0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal =
new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text = (
string)control.GetType().GetProperty("SelectedItem").GetValuecontrol,null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else
if
(control.GetType().GetProperty("Text") != null)
{
LiteralControl literal =
new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (
string)control.GetType().GetProperty("Text").GetValue(control,null);
control.Parent.Controls.Remove(control);
}
}
return;
}
</script>
<
html>
<
body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<
form id="frm" runat="server">
<
asp:Button id="Button1" runat="server" Text="Export to Excel"
OnClick="Button1_Click"></asp:Button><BR>
<
asp:Datagrid id="dg" runat="server" AutoGenerateColumns="True"
AllowSorting="true" AllowPaging="true"CellPadding="3" PageSize=3>
<
columns>
<
asp:TemplateColumn>
<
ItemTemplate>
<
asp:LinkButton runat="server" CommandName="Edit"CausesValidation="false" ID="btnView"Text="Edit"/>
</
ItemTemplate>
</
asp:TemplateColumn>
</
columns>
</
asp:datagrid>
<
BR>
</form>
</
body>
</
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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dipal Choksi
Dipal Choksi has over 10 years of industry experience in team-effort projects and also as an individual contributor. She has been working on the .Net platform since the beta releases of .Net 1.0.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Resource: Exporting to Word and Text by Mahesh On November 14, 2006

Here is a good resource on how to export to Excel, Word, and Text files:

http://www.codersource.net/published/view/283/exporting_data_grid_to_excel.aspx

Reply | Email | Modify 
Resource: Exporting to Word and Text by Mahesh On November 14, 2006

Here is a good resource on how to export to Excel, Word, and Text files:

http://www.codersource.net/published/view/283/exporting_data_grid_to_excel.aspx

Reply | Email | Modify 
Re: Resource: Exporting to Word and Text by karthik On January 24, 2007

I am getting a error when i click open in the dialog box it says file not found in the temporary folder. The save option works fine.

 

Reply | Email | Modify 
Regards this article by Sobeer On March 23, 2007
Thanks Dipal, This is a great help!
Reply | Email | Modify 
Regards this article by Sobeer On March 23, 2007
Thanks Dipal This is a great help! Sobeer
Reply | Email | Modify 
Display special characters in excel spreadsheet by smriti On July 26, 2007
I have displayed temperature on my web page with the unit &degF. For that i have added the following to the code. "  & deg F"...this works fine but when i do an export to excel "& deg F" is displayed as the unit in the excel spreadsheet..i would want the character degree to be displayed in the excel file too..How can i do that ?
Reply | Email | Modify 
Display characters in excel by smriti On July 26, 2007
I have displayed temperature on my web page with the unit °F. For that i have added the following to the code.   & deg F...this works fine but when i do an export to excel "& deg F" is displayed as the unit in the excel spreadsheet..i would want the character degree to be displayed in the excel file too..How can i do that ?
Reply | Email | Modify 
Very good Article by VVSN On August 17, 2007
normal datagrid exporting to excel is easy but datagrid with link buttons is not easy for that you have provided a very good method thanks for that
Reply | Email | Modify 
Very good Article by VVSN On August 17, 2007
normal datagrid exporting to excel is easy but datagrid with link buttons is not easy for that you have provided a very good method thanks for that
Reply | Email | Modify 
HOW TO REMOVE BUTTONFIELD by hakeem On September 10, 2007
HI ALL,THANKS FOR UR POST WHICH HELP ME ALOT,I WANT THE CODE WHERE INSTEAD OF MAKING THE BUTTONFIELD DISPLAED LIKE A TEXT IN EXCEL REPORT CAN WE DO LIKE THE BUTTONFIELDS SHOULD BE BE EXPORTED OR HIDE SO THAT THE EXCEL SHEET SHOULD HAVE ONLY DATA. MY GRIDVIEW HAS 7 COLUMNS AND OUT OF THEM 3 ARE BUTTONFIELD. SO PLZ PLZ HELP ME IN THIS. THANKS IN ADVANCE, KAZMI
Reply | Email | Modify 
Problem exporting gridview bound column data to Word by ajay On October 9, 2007
While Exporting gridview bound column data , How to hide the TemplateField HeaderText Is there any sol's .pls help me . with regards Ajay
Reply | Email | Modify 
Problem exporting gridview bound column data to Word by ajay On October 9, 2007
While Exporting gridview bound column data , How to hide the TemplateField HeaderText Is there any sol's .pls help me . with regards Ajay
Reply | Email | Modify 
Problem exporting gridview bound column data to Word by ajay On October 9, 2007
While Exporting gridview bound column data , How to hide the TemplateField HeaderText Is there any sol's .pls help me . with regards Ajay
Reply | Email | Modify 
Problem exporting gridview bound column data to Word by ajay On October 9, 2007
While Exporting gridview bound column data , How to hide the TemplateField HeaderText Is there any sol's .pls help me . with regards Ajay
Reply | Email | Modify 
Problem exporting gridview bound column data to Word by ajay On October 9, 2007
While Exporting gridview bound column data , How to hide the TemplateField HeaderText Is there any sol's .pls help me . with regards Ajay
Reply | Email | Modify 
Error,Exporting gridview values to excel by Kumaresh On November 24, 2007
Error when i run code to export gridview values to excel: Control 'dg' of type 'GridView' must be placed inside a form tag with runat=server. Rectify my error
Reply | Email | Modify 
Re: Error,Exporting gridview values to excel by suresh On July 15, 2009
I had the same problem please help me.
Reply | Email | Modify 
Real XML/xlsx export to Excel by Ettore On February 7, 2008
I think this is the usual HTML export of a Gridview to Excel. Take a look at http://www.gridviewtoexcel.com ! You'll find a tool which allows to export data from a Gridview and its datasource to real Excel XML or XLSX formats.
Reply | Email | Modify 
Export to full-function Excel file by Tim On March 10, 2008
OfficeWriter is a commercial product, but it allows you to read, write, or modify binary Excel files on a web server. It also reads and writes Word files.
Reply | Email | Modify 
Work with XLS/CSV/HTML/XLSX files by Filip On March 25, 2008
GemBox.Spreadsheet - Read/Write XLSX File - Visual Basic, C# and ASP.NET Component is also commercial component but it has a Free Spreadsheet component that can be used in your applications. It comes with 150 rows limit.
Reply | Email | Modify 
Resource: Exporting to Word and Text by Francio On December 11, 2008
With master pages had several issues like gridview is out of form tag etc etc.. below code works for me. protected void cmdExportToExcel_Click(object sender, EventArgs e) { Response.Clear(); Response.Buffer = true; Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); System.Web.UI.HtmlControls.HtmlForm frm = new HtmlForm(); this.Controls.Add(frm); frm.Controls.Add(grdViewPlan); frm.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); }
Reply | Email | Modify 
DataGrid to excel by steven On March 14, 2009
Response.Clear(); Response.Buffer= true; Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); DataGrid dg = new DataGrid(); dg.DataSource = GetDataSource(); //??DataSet?DataTable dg.DataBind(); dg.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End();
Source Code
Reply | Email | Modify 
Creating PDF file using ASP.net by Thomas On March 31, 2009
To create PDF file using asp.net http://techdotnets.blogspot.com/
Reply | Email | Modify 
help me! by suresh On July 15, 2009
what is the code for asp.net2.0 with vb soure code....
Reply | Email | Modify 
Export to Excel by S On October 3, 2009

Hi ,

                 My Datatable contains value 002 whenever i download in Datatable to Excel. It shows only 2 but i need the following format 002 in Excel download file(ASP.Net-05, C#).Is it possible. plz replay ...

 

Regards,

Tankxx.

Reply | Email | Modify 
xcv by anu On December 12, 2009

cxzvvzczxcvzxc
Reply | Email | Modify 
cannot export data in all the pages in the datagrid by Shailender On May 28, 2010

Cannot export data in all the pages on the datagrid,able to export only first page.
i have paging on datagrid,need to get all data to excel
can u give suggestion

Reply | Email | Modify 
solve this error by jitendra On July 21, 2010
try { Literal.Text =(string)control.GetType().GetProperty("SelectedItem").GetValue(control, null); } catch { }
Reply | Email | Modify 
export to excel by jason On August 2, 2010
I use a best tool for creating an Excel Spreadsheet with C#, it can reading and writing to excel 97 ~ 2010 from c#,extremely easy to use,I use it long time quit good. Spire.XLS
Reply | Email | Modify 
Simpler way by Filip On September 21, 2010
Hello

There is a simpler way to export DataGrid to Excel from your Excel ASP.NET application with use of this excellent Excel .NET library.

Here is a sample Excel C# code:


// Get DataTable that DataGrid is bound to.

var dataTable = (DataTable)dataGrid.DataSource;

 

// Create new ExcelFile.

var ef = new ExcelFile();

// Add new worksheet to the file.

var ws = ef.Worksheets.Add(dataTable.TableName);

// Insert the data from DataTable to the worksheet starting at cell "A1".

ws.InsertDataTable(dataTable, "A1", true);

 

// Stream file to browser.

Response.Clear();

Response.ContentType = "application/vnd.ms-excel";

Response.AddHeader("Content-Disposition", "attachment; filename=Employee.xls");

ef.SaveXls(Response.OutputStream);

Response.End();

Reply | Email | Modify 
Regards this article by Ade On October 6, 2011
hi.. choksi,, can i learn your code?? and can i download your source file? Regards, Ade Ruyani
Reply | Email | Modify 
Not properly working by christo On November 29, 2011
hi buddy, its working for literal control,but i have attached lot of sublinks.that should be not show in excel...
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.