Export a DataSet to Excel or Word
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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