public void ToExcel(DataTable dt,HttpContext content)
{
string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
content.Response.Clear();
string fileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(filename));
content.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
content.Response.ContentType = "applicationnd.ms-excel";
content.Response.Charset = "utf-8";
StringBuilder s = new StringBuilder();
s.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"textml; charset=utf-8\"></head><body>");
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htw);
content.Response.Write(sw.ToString());
content.Response.End();
}ASP.ENT c# 将数据导出为Excel
最新推荐文章于 2025-12-01 05:49:10 发布
本文介绍了一种将DataTable数据导出为Excel文件的方法。通过设置HTTP响应头、使用StringBuilder拼接HTML表格、利用GridView控件渲染数据,最终完成数据导出。此方法支持UTF-8编码,并能确保浏览器正确下载生成的.xls文件。

348

被折叠的 条评论
为什么被折叠?



