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

       }
   }
相关推荐
Tisfy2 小时前
LeetCode 1927.求和游戏:抵消+看最值
java·leetcode·游戏·题解·博弈论
「QT(C++)开发工程师」7 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天8 小时前
0 初识C++
开发语言·c++
FfHUCisI8 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI8 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
秋饼8 小时前
JDK 27 企业级 AI 服务落地实战:G1 默认、紧凑对象头、后量子 TLS 与 JFR 脱敏全解析
java·ai·技术分享·后端开发
卓怡学长9 小时前
w176基于SpringBoot的医院管理系统
java·spring boot·spring·maven·intellij-idea
lemon_sjdk9 小时前
ObjectProperty
java·开发语言·算法
大模型码小白9 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring