public static class ExportToExcel
{
///
/// This Method takes DataTable and Page as input parameter and
/// renders the converted excel data to given page instance.
///
/// DataTable instance
/// The Sytem.Web.UI.Page instance.
public static void Export(string fileName, GridView gv, string title)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.Charset = "";
//HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.ContentType = "application/vnd.xls";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter htw = new HtmlTextWriter(sw);
try
{
// render the table into the htmlwriter
RenderGrid(gv).RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write("" + title + "");
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
finally
{
htw.Close();
}
}
}
More Coding Mehtods:
http://blogs.msdn.com/b/erikaehrli/archive/2009/01/30/how-to-export-data-to-excel-from-an-asp-net-application-avoid-the-file-format-differ-prompt.aspx
No comments:
Post a Comment