First drag the gridview control on aspx page
then add button control
<asp:Button onclick="Button1_Click" text="Export to Excel" runat="server" id="Button1"/>
and on .cs page paste this code
protected void Button1_Click(object sender, EventArgs e)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "Exported"));
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
Table table = new Table();
foreach (GridViewRow row in gvBankReco.Rows)
{
VerifyRenderingInServerForm(row);
table.Rows.Add(row);
}
table.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
public override void VerifyRenderingInServerForm(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as
LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as
ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as
HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as
DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as
CheckBox).Checked ? "כן" : "ל×"));
}
if (current.HasControls())
{
VerifyRenderingInServerForm(current);
}
}
}
I hope by doing this your problem will be solve.