Look at this code. It might be helpful for you.
private DataTable SourceForGrid
{
get { return (DataTable)Session["SourceForGrid"]; }
set { Session["SourceForGrid"] = value; }
}
protected void btnExport_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvSource.Rows)
{
CheckBox chk = (CheckBox)gvr.FindControl("chkBxExport");
if (chk.Checked)
{
id += gvSource.DataKeys[gvr.RowIndex].Value.ToString() + ",";
}
id = id.TrimEnd(',');
}
if (id.Length != 0)
{
var query = from result in ((DataTable)Session["SourceForGrid"]).AsEnumerable()
where id.Contains(Convert.ToString(result.Field<int64>("ads_src_id")))
select result;
GenerateExcel(query.CopyToDataTable());
}
else
{
Response.Write("alert('Please select source for export');");
}
}
public static void GenerateExcel(DataTable dtSource)
{
StringBuilder sbDocBody = new StringBuilder(); ;
try
{
// Declare Styles
sbDocBody.Append("");
sbDocBody.Append(".Header { background-color:Navy; color:#ffffff; font-weight:bold;font-family:Verdana; font-size:12px;}");
sbDocBody.Append(".SectionHeader { background-color:#8080aa; color:#ffffff; font-family:Verdana; font-size:12px;font-weight:bold;}");
sbDocBody.Append(".Content { background-color:#ccccff; color:#000000; font-family:Verdana; font-size:12px;text-align:left}");
sbDocBody.Append(".Label { background-color:#ccccee; color:#000000; font-family:Verdana; font-size:12px; text-align:right;}");
sbDocBody.Append("");
//
StringBuilder sbContent = new StringBuilder(); ;
sbDocBody.Append("
");
sbDocBody.Append("
");
sbDocBody.Append("");
//
if (dtSource.Rows.Count > 0)
{
sbDocBody.Append("");
sbDocBody.Append("");
sbDocBody.Append("");
sbDocBody.Append("");
for (int i = 0; i < dtSource.Columns.Count; i++)
{
sbDocBody.Append("");
}
sbDocBody.Append("");
//
// Add Data Rows
for (int i = 0; i < dtSource.Rows.Count; i++)
{
sbDocBody.Append("");
sbDocBody.Append("");
for (int j = 0; j < dtSource.Columns.Count; j++)
{
sbDocBody.Append("");
}
sbDocBody.Append("");
}
sbDocBody.Append("");
//
// Add Column Headers
sbDocBody.Append(" | | | " + dtSource.Columns[i].ToString().Replace(".", " ") + "
| | " + dtSource.Rows[i][j].ToString() + " | ");
sbDocBody.Append(" | ");
sbDocBody.Append(" |
");
}
//
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
//
HttpContext.Current.Response.AppendHeader("Content-Type", "application/ms-excel");
HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=Ads_Src.xls");
HttpContext.Current.Response.Write(sbDocBody.ToString());
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
// Ignore this error as this is caused due to termination of the Response Stream.
}
}