freemarker 读取template.xml ,通过response 输出文件,解决中文乱码问题

采用

try (Writer writer = new OutputStreamWriter(os, "UTF-8"))

UTF-8 内容转换
复制代码
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            // fileName = "中文.xls";
             try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            //response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);//
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

 public void xml2XmlOutFromResources(HttpServletResponse response, Map<String, Object> dataMap, String templetFile, String fileName) throws IOException, TemplateException {

       //设置响应头
       ExportExcel.setResponseHeader(response, fileName);

       Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);

       configuration.setDefaultEncoding("UTF-8");
       configuration.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(), "");
       Template template = null;
       try {
           template = configuration.getTemplate("templates/exportTemplate.xml","UTF-8");
       } catch (Exception e) {
           e.printStackTrace();
       }

       //模板和数据模型合并生成文件
       OutputStream os = null;

       try {
           os = response.getOutputStream();
           try (Writer writer = new OutputStreamWriter(os, "UTF-8")) {
               template.process(dataMap, writer);
           }

       } catch (Exception ex) {

       } finally {
           try {

               if (os != null) {
                   os.close();
               }

           } catch (IOException e) {
               e.printStackTrace();
           }

       }
   }
相关推荐
AAA简单玩转程序设计2 分钟前
救命!Java 进阶居然还在考这些“小儿科”?
java·前端
总是学不会.8 分钟前
【JUC编程】多线程学习大纲
java·后端·开发
MediaTea10 分钟前
思考与练习(第十章 文件与数据格式化)
java·linux·服务器·前端·javascript
Matlab光学16 分钟前
MATLAB仿真:离轴干涉法实现光学全息加密与解密
开发语言·matlab
7澄116 分钟前
Maven 项目拆分与聚合实战:分层架构下的多模块开发
java·架构·maven·service·dao·pojo·数据库连接
一起养小猫22 分钟前
LeetCode100天Day4-盛最多水的容器与两数之和II
java·数据结构·算法·leetcode
小鸡吃米…25 分钟前
Python - JSON
开发语言·python·json
ZBritney27 分钟前
JAVA中的多线程
java
JAVA+C语言29 分钟前
C#——接口
开发语言·c#
黎雁·泠崖31 分钟前
吃透指针通用用法:回调函数与 qsort 的使用和模拟
c语言·开发语言