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();
           }

       }
   }
相关推荐
bang冰冰5 分钟前
Trae工具安装和使用教程(新手零基础入门,全程无坑)
java·人工智能·python
User_芊芊君子6 分钟前
聊聊自由开发者常用的学习机会全解析
开发语言·人工智能·python
阿丰资源7 分钟前
基于Spring Boot的网上摄影工作室系统(源码一键运行)
java·spring boot·后端
阿维的博客日记16 分钟前
容器是怎么管理 Bean 的?
java·bean
AI人工智能+电脑小能手29 分钟前
【大白话说Java面试题】【Java基础篇】第40题:Java中的深拷贝和浅拷贝有什么区别
java·开发语言·后端·面试
@小匠32 分钟前
云之家表单数据解析 skills (yzj-form-parser)
java
云烟成雨TD36 分钟前
Spring AI Alibaba 1.x 系列【48】状态图编译配置类:CompileConfig 源码解析
java·人工智能·spring
xh didida1 小时前
算法 -- 位运算
开发语言·c++·算法
谙弆悕博士1 小时前
快速学C语言——第2章:编程规范与代码风格
服务器·c语言·开发语言·经验分享·程序人生·学习方法·业界资讯
曹牧1 小时前
Oracle:将包含属性(Attributes)的 XML 数据解析为表格数据
xml·数据库·oracle