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$的名称确实乱码,不知道该怎么弄。。

  • 相关阅读:
    众包兼职平台有哪些?
    提高页面速度的10种相对简单方法
    如何设计第三方账号登陆
    Nginx的配置参数中文说明
    确定你已经彻底搞懂Nginx了
    云编程,这是我见过最优雅的Web云端集成开发IDE-Cloud Studio
    Excel制作三级下拉菜单
    Excel多人共享
    spring_2_注入详解
    spring_1_工厂与第一个 Spring 程序
  • 原文地址:https://www.cnblogs.com/bryant/p/1558793.html
Copyright © 2011-2022 走看看