DataTable转Excel

响应流方式,适用于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();
            }
        }

posted @ 2016-12-03 09:34  牧羊人8683  阅读(141)  评论(0编辑  收藏  举报