C# web DataTable 导出成Excel

 private static void EportAllDataToExcel(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";
            curContext.Response.AddHeader("Content-Disposition", "attachment;filename=1.xls");
            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();
            curContext.Response.End();
        }


注意:在使用asp.net制作导出时,若页面导出控件的在 <asp:UpdatePanel > 控件中时,导出不能成功,用firefox或google chrome 的控制台进行监控时 可以看到页面报:

Sys.WebForms.PageRequestManagerParserErrorException:The message received from the server
count not be parsed.Common causes for this error are when the response is modified by calls to response.Write(),response filters,HttpModules,or server trace is enabled.的错误。

 

此时解决方法:在<asp:UpdatePanel > 控件中加入

<Triggers>
       <asp:PostBackTrigger ControlID="buttonname" />  <!-buttonname 为要触发的事件控件ID->

 </Triggers>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值