Wednesday, July 14, 2010

Export to excel from Sharepoint Reports

protected void btnSendtoExcel_Click1(object sender, EventArgs e)
{
try
{
if (grdResultView.Rows.Count != 0)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", "KCADetails.xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";

using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a table to contain the grid
Table table = new Table();
table.GridLines = GridLines.Both;
// add each of the data rows to the table
table.Rows.Add(grdResultView.HeaderRow);
if (grdResultView.Rows.Count != 0)
{
foreach (GridViewRow row in grdResultView.Rows)
{
//GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
// render the table into the htmlwriter
table.RenderControl(htw);

// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
}
}
catch (Exception ex)
{ }
}

No comments:

Post a Comment