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

       }
   }
相关推荐
搏博5 分钟前
WPS中代码段的识别方法及JS宏实现
开发语言·javascript·wps
vortex510 分钟前
Bash fork 炸弹 —— :(){ :|:& };:
运维·服务器·开发语言·网络安全·bash
小伍_Five15 分钟前
spark数据处理练习题详解【下】
java·大数据·spark·scala
Pacify_The_North27 分钟前
【进程控制二】进程替换和bash解释器
linux·c语言·开发语言·算法·ubuntu·centos·bash
xiaohanbao0941 分钟前
day29 python深入探索类装饰器
开发语言·python·学习·机器学习·pandas
L汐1 小时前
02 K8s双主安装
java·容器·kubernetes
wuqingshun3141591 小时前
经典算法 (A/B) mod C
c语言·开发语言·c++·算法·蓝桥杯
半青年1 小时前
Qt图表库推荐指南与分析
c语言·开发语言·javascript·c++·qt·信息可视化
jackson凌1 小时前
【Java学习笔记】【第一阶段项目实践】房屋出租系统(面向对象版本)
java·笔记·学习
艾米莉亚糖1 小时前
解决qt.network.ssl: QSslSocket::connectToHostEncrypted: TLS initialization failed
开发语言·qt·ssl