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

       }
   }
相关推荐
夏婵语冰2 小时前
实用R语言机器学习指南:从数据预处理到模型实战(附配套学习资源)
开发语言·学习·r语言
cyforkk3 小时前
ArrayList vs LinkedList:底层原理与实战选择指南
java
孟婆来包棒棒糖~4 小时前
泛型与反射
java·反射·javase·泛型
牛角上的男孩4 小时前
apt update Ign and 404 Not Found
开发语言·数据库
A尘埃4 小时前
Spring Event 企业级应用
java·spring·event
yzzzzzzzzzzzzzzzzz5 小时前
JavaScript 操作 DOM
开发语言·javascript·ecmascript
海绵宝宝汉堡包6 小时前
c# 项目 文件夹
开发语言·c#
YuTaoShao6 小时前
【LeetCode 热题 100】139. 单词拆分——(解法一)记忆化搜索
java·算法·leetcode·职场和发展
Best_Liu~7 小时前
策略模式 vs 适配器模式
java·spring boot·适配器模式·策略模式
小白要加油努力7 小时前
C++设计模式--策略模式与观察者模式
开发语言·c++·设计模式