write it on your .aspx page :
<asp:ImageButton ID="btnExportToExcelAbv" ImageUrl="~/Images/export-to-excel.gif"
runat="server" OnClick="btnExportToExcel_Click" />
<br />
<div id="dvPrintXLFull" runat="server">
<asp:gridview id="grd1" runat="server" xmlns:asp="#unknown"></asp:gridview>
</div>
and code behind is after binding the grid :
protected void btnExportToExcel_Click(object sender, ImageClickEventArgs e)
{
GridExportToExcel();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void GridExportToExcel()
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename= Stock_Ledger.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
#region ExcelExportCode
dvPrintXLFull.RenderControl(htmlWrite);
/
Response.Write(stringWrite.ToString());
Response.End();
#endregion
}
Hope this will help you.
Don't forget to mark as answer if it helps. :)