Export Gridview to Excel in asp.net and c#

In this article,I will explain how to export GridView Data to Excel file.Exporting Grid view to excel report is one of the most common requirement in real world.This article implement some common ways of exporting Grid view data display on web page to excel.

In this article, i am assuming that you have taken a GridView named GridView1 and a Button named lbExportInExcel_Click1.

aspx code.
<asp:GridView ID="GridView1" runat="server" EnableTheming="False" OnRowDataBound="GridView1_RowDataBound"
<HeaderStyle CssClass="ReportHeader" Width="80px" /
<RowStyle CssClass="ReportText" />
<PagerStyle CssClass="ReportHeader" />
<AlternatingRowStyle CssClass="ReportText" />
<EmptyDataRowStyle CssClass="ReportText" />
<span style="font-size: 11pt; color: #ff0033"><strong>No Records ........!!</strong></span>
<asp:BoundField HeaderText="Sr. No." />

.cs code

//connection string has written in another class.
string conStr = FetchConnection.FetchConnectionString().ToString();
//Bind Gridview from database
void GridViewEmp()
DataSet Ds = new DataSet();
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
string str = "SELECT * from EmployeeTbl"
Ds = SqlHelper.ExecuteDataset(conStr, CommandType.Text, str);
GridView1.DataSource = Ds;

protected void lbExportInExcel_Click1(object sender, ImageClickEventArgs e)
string attachment = "attachment; filename=" + "Emp Report" + ".xls";
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
public override void VerifyRenderingInServerForm(Control control)
// Confirms that an HtmlForm control is rendered for the
//specified ASP.NET server control at run time.

Reference: http://aspdotnetcode.blogspot.com/2009/04/export-gridview-to-excel-and-pdf-file.html


Guest Author: jismyva30 May 2012

How can i reapeat column headers in all the pages

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: