Skip to content

Instantly share code, notes, and snippets.

@aromig
Last active February 16, 2016 21:12
Show Gist options
  • Save aromig/92e63788c46a96ce8bc6 to your computer and use it in GitHub Desktop.
Save aromig/92e63788c46a96ce8bc6 to your computer and use it in GitHub Desktop.
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