Skip to content

Instantly share code, notes, and snippets.

@aromig

aromig/ExportDataSet.cs

Last active Feb 16, 2016
Embed
What would you like to do?
Export a DataSet to Excel or Word
public static void ExportDataSet(DataSet ds, string format, string filename, bool boolGridLines, string caption)
{
// format = "ms-excel", "ms-word"
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd." + format;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + filename);
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
if (caption != "")
{
dg.Caption = caption;
}
dg.GridLines = boolGridLines ? GridLines.Both : GridLines.None;
if (format == "ms-word")
{
dg.Width = Unit.Percentage(80);
dg.HorizontalAlign = HorizontalAlign.Center;
}
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
dg.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
dg.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment