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

       }
   }
相关推荐
weixin19970108016几秒前
加盟网 item_search - 根据关键词获取行业列表接口对接全攻略:从入门到精通
java·python
EliseL几秒前
SuperMap iObjects Java 如何将3DTiles数据转换为S3M三维瓦片
java·3d·三维
cyforkk1 分钟前
11、Java 基础硬核复习:常用类和基础API的核心逻辑与面试考点
java·python·面试
全栈师3 分钟前
java和C#的基本语法区别
java·开发语言·c#
JHC00000012 分钟前
智能体造论子--简单封装大模型输出审核器
开发语言·python·机器学习
【赫兹威客】浩哥12 分钟前
可食用野生植物数据集构建与多版本YOLO模型训练实践
开发语言·人工智能·python
沐知全栈开发15 分钟前
Java 封装
开发语言
2301_8107301021 分钟前
python第三次作业
开发语言·python
小马爱打代码22 分钟前
Spring AI 实战:Agent 基础搭建与核心能力解析
java·人工智能·spring
郝学胜-神的一滴23 分钟前
Python List操作:+、+=、extend的深度解析
开发语言·数据结构·python·程序人生·架构·list