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

       }
   }
相关推荐
wjs202413 小时前
JavaScript for 循环详解
开发语言
东华万里13 小时前
第十五讲 指针 从本质吃透 C 语言指针(上)
c语言·开发语言
雨雨雨雨雨别下啦13 小时前
Spring AOP概念
java·后端·spring
on the way 12313 小时前
day04-Spring之Bean的生命周期
java·后端·spring
代码笔耕13 小时前
面向对象开发实践之消息中心设计(二)
java·后端·架构
moxiaoran575313 小时前
Go 语言指针
开发语言·golang
爱吃大芒果13 小时前
Flutter 网络请求完全指南:Dio 封装与拦截器实战
开发语言·javascript·flutter·华为·harmonyos
云水木石13 小时前
Rust 语言开发的 Linux 桌面来了
linux·运维·开发语言·后端·rust
要开心吖ZSH13 小时前
应用集成平台-系统之间的桥梁-思路分享
java·kafka·交互
TsengOnce13 小时前
阿里云ECS多版本JDK切换
java·python·阿里云