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"
Width="100%">
<HeaderStyle CssClass="ReportHeader" Width="80px" /
<RowStyle CssClass="ReportText" />
<PagerStyle CssClass="ReportHeader" />
<AlternatingRowStyle CssClass="ReportText" />
<EmptyDataRowStyle CssClass="ReportText" />
<EmptyDataTemplate>
<span style="font-size: 11pt; color: #ff0033"><strong>No Records ........!!</strong></span>
</EmptyDataTemplate>
<Columns>
<asp:BoundField HeaderText="Sr. No." />
</Columns>
</asp:GridView>
.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;
GridView1.DataBind();
}
protected void lbExportInExcel_Click1(object sender, ImageClickEventArgs e)
{
string attachment = "attachment; filename=" + "Emp Report" + ".xls";
Response.Clear();
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);
reportName.RenderControl(htmlWrite);
rowInfo.RenderControl(htmlWrite);
rowGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
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
How can i reapeat column headers in all the pages