Here i have explained how to Export Gridview Data to Excel in Asp.Net C#.

Step 1) Add HTML:

<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
</asp:GridView>

Step 2) Import Namespaces

using System;
using System.Data;
using System.IO;
using System.Web.UI;

Step 3) C#

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));

dt.Rows.Add(1, "Imran", "B.Tech", "Delhi");
dt.Rows.Add(2, "Ram", "MCA", "Allahabad");
dt.Rows.Add(3, "Rajesh", "B.Tech", "Hydrabad");
dt.Rows.Add(4, "Erdogan", "MSC", "Ankra");
dt.Rows.Add(5, "Abudullah", "CA", "Mumbai");
dt.Rows.Add(6, "Bahar", "BA", "Tehran");
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{

}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customer.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvDetails.AllowPaging = false;
BindGridview();

gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF");

for (int i = 0; i < gvDetails.HeaderRow.Cells.Count; i++)
{
gvDetails.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gvDetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Screenshot

Add Comments