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();
            }
        }

转载于:https://www.cnblogs.com/L-Blews/p/6128014.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值