Use this code for export to excel gridview data. Make sure you pass correct datasource to dt(You can provide same datasource which you provide to gridview).
onbuttonclick()
{
datatable dt= new datatable();
dt= obj.getdataforexcel();
ExportToExcel(dt);
}
public void ExportToExcel(DataTable dt)
{
string XlsPath = "Sheet1";
string attachment = string.Empty;
HttpContext context = HttpContext.Current;
if (XlsPath.IndexOf("\\") != -1)
{
string[] strFileName = XlsPath.Split(new char[] { '\\' });
attachment = "attachment; filename=" + strFileName[strFileName.Length - 1] + ".xls";
}
else
attachment = "attachment; filename=" + XlsPath + ".xls";
try
{
context.Response.ClearContent();
context.Response.AddHeader("content-disposition", attachment);
context.Response.ContentType = "application/vnd.ms-excel";
string tab = string.Empty;
foreach (DataColumn datacol in dtRecords.Columns)
{
context.Response.Write(tab + datacol.ColumnName);
tab = "\t";
}
context.Response.Write("\n");
foreach (DataRow dr in dtRecords.Rows)
{
tab = "";
for (int j = 0; j < dtRecords.Columns.Count; j++)
{
context.Response.Write(tab + Convert.ToString(dr[j]));
tab = "\t";
}
context.Response.Write("\n");
}
context.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}