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

       }
   }
相关推荐
笑鸿的学习笔记9 分钟前
C++笔记之信号量和引用计数的概念是否等价?
java·c++·笔记
zbguolei1 小时前
第002篇 · 战火中的电子黎明
开发语言·php
IManiy1 小时前
AgentScope Java 2.0(四)上下文、状态与中间件
java
sean_wang121 小时前
Rust 轻量级虚拟机 smolvm 实战:200ms 冷启动、OCI 镜像直跑、单文件打包
开发语言·后端·rust·大鲸华章
战6172 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
青山木2 小时前
JVM 类加载全解:Class 文件结构、加载链接初始化与双亲委派
java·jvm·后端·类加载·双亲委派机制
郝学胜-神的一滴2 小时前
量化交易从入门到精通 05:策略从哪来
开发语言·python·numpy·pandas·scikit-learn·matplotlib·scipy
Nazarick2 小时前
从 fetch 到 then:Demo在线订单系统 Ajax 回调的逐帧拆解
java·javascript·ajax·web
智购科技自动售货机厂家2 小时前
自动售货机外设接口与总线设计实战:串口、CAN 与 GPIO 的分工~YH
java·大数据·服务器·数据库·人工智能·单片机·嵌入式硬件
zbguolei3 小时前
第001篇 · 算盘与差分机
开发语言·php