zoukankan      html  css  js  c++  java
  • 采用UTF8格式导出Excel存在乱码解决方法

    目前我们开发Excel导出时,多数使用ExportToExcelCommon类导出Excel,通常情况下不会产生乱码,但在某些时候还是会产生乱码。解决方法很简单,只需要在ExportToExcel()方法中多加一句代码即可,ExportToExcel()方法如下:
    
    string fileName;
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Charset = "UTF-8";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.UTF8;
    
                fileName = string.Format("AOMS Export-{0:yyyy-MM-dd_HH_mm_ss}.xls", DateTime.Now);
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
                //设置输出文件类型为excel文件。
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                StringWriter tw = new System.IO.StringWriter();
                HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
                gvw.RenderControl(hw);
                if (!string.IsNullOrEmpty(title))
                {
                    HttpContext.Current.Response.Write("<b><center><font size=3 face=Verdana color=#0000FF>" + title + "</font></center></b>");
                }
                HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/>");
                HttpContext.Current.Response.Write(tw.ToString());
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.Close();
                HttpContext.Current.Response.End();
    
                gvw.Dispose();
                tw.Dispose();
                hw.Dispose();
    
                gvw = null;
                tw = null;
             hw = null;
    注意上述代码的重点在于这一句:
    HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/>");
    在导出方法中加入这一句代码,即可防止采用UTF-8格式导出Excel时出现乱码。
  • 相关阅读:
    基于接口的动态代理和基于子类的动态代理
    JDBC连接数据库
    关于使用Binlog和canal来对MySQL的数据写入进行监控
    使用VMware12在CentOS7上部署docker实例
    VMWare12pro安装Centos 6.9教程
    读《Java并发编程的艺术》学习笔记(十)
    读《Java并发编程的艺术》学习笔记(九)
    读《Java并发编程的艺术》学习笔记(八)
    读《Java并发编程的艺术》学习笔记(七)
    读《Java并发编程的艺术》学习笔记(六)
  • 原文地址:https://www.cnblogs.com/Areas/p/2792095.html
Copyright © 2011-2022 走看看