public void DataTableToExcel(System.Data.DataTable dt, string FileName)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid excel = new DataGrid();
System.Web.UI.WebControls.TableItemStyle headerStyle = new TableItemStyle();
headerStyle.BackColor = System.Drawing.Color.LightGray;
headerStyle.Font.Bold = true;
headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
excel.HeaderStyle.MergeWith(headerStyle);
excel.GridLines = GridLines.Both;
excel.HeaderStyle.Font.Bold = true;
excel.DataSource = dt.DefaultView; //输出DataTable的内容
excel.DataBind();
excel.RenderControl(htmlWriter);
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename='" + FileName + ".xls'");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
HttpContext.Current.Response.ContentType = ".xls";
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();
}
DataTable 转化为Excel
最新推荐文章于 2022-07-21 08:32:17 发布