响应流方式,适用于APS.NET Web开发
public void DataTableToExcel(DataTable dt)
{
System.Web.UI.WebControls.DataGrid dgExport = null;
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWrite = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
if (dt.Rows.Count > 0)
{
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "utf-8";
string fileName = "JX_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
curContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
strWrite = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWrite);
dgExport = new System.Web.UI.WebControls.DataGrid();
dgExport.DataSource = dt.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWrite);
//curContext.Response.Flush(); // 如果此方法是在其他方法中被调用使用,那请你注释这一行,不然会报错提示“会话状态已创建一个会话 ID,但由于响应已被应用程序刷新而无法保存它。”
curContext.Response.End();
}
}
转载于:https://www.cnblogs.com/L-Blews/p/6128014.html