zoukankan      html  css  js  c++  java
  • datatable中导出excel文件

      public void DataTableExcel(System.Data.DataTable dtData)
        {
            System.Web.UI.WebControls.DataGrid dgExport = null;
            // 当前对话
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                // 设置编码和附件格式
                curContext.Response.ContentType = "application/vnd.ms-excel";
                curContext.Response.AppendHeader("Content-Disposition", "attachment;Filename=" + System.Web.HttpUtility.UrlEncode(this.ddlType.Text.Trim(), System.Text.Encoding.UTF8) + ".xls");

                curContext.Response.ContentEncoding = System.Text.Encoding.UTF7;
                curContext.Response.Charset = "GB2312";

                // 导出excel文件
                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
                dgExport = new System.Web.UI.WebControls.DataGrid();
                dgExport.DataSource = dtData.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.DataBind();

                // 返回客户端
                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }


    起初用了utf-8格式编码,在数据量稍微大一点的时候,导出是没有问题的,但有时候数据量比较少的时候,导出会有乱码,最后我采用了UTF-7格式编码,问题就解决了,虽然保存的文件名没有乱码了,导出的文件也没乱码了,可是那个sheet$的名称确实乱码,不知道该怎么弄。。

  • 相关阅读:
    React学习笔记(六)事件处理
    React学习笔记(五)State&声明周期
    学会装逼,你的人生可能会开挂
    Go指南
    JavaScript检测数据类型
    $.on()方法和addEventListener改变this指向
    JavaScript返回上一页
    js继承
    js原型二
    全局变量与局部变量
  • 原文地址:https://www.cnblogs.com/bryant/p/1558793.html
Copyright © 2011-2022 走看看