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

       }
   }
相关推荐
Frank Castle8 分钟前
【C语言】详解C语言字节打包:运算符优先级、按位或与字节序那些坑
c语言·开发语言
kk哥88999 分钟前
分享一些学习JavaSE的经验和技巧
java·开发语言
2501_9403152625 分钟前
【无标题】1.17给定一个数将其转换为任意一个进制数(用栈的方法)
开发语言·c++·算法
栈与堆26 分钟前
LeetCode 21 - 合并两个有序链表
java·数据结构·python·算法·leetcode·链表·rust
lagrahhn36 分钟前
Java的RoundingMode舍入模式
java·开发语言·金融
鸽鸽程序猿41 分钟前
【JavaEE】【SpringCloud】注册中心_nacos
java·spring cloud·java-ee
云上凯歌1 小时前
01 GB28181协议基础理解
java·开发语言
FakeOccupational1 小时前
【电路笔记 PCB】Altium Designer : AD使用教程+Altium Designer常见AD操作命令与流程
开发语言·笔记
Coder_Boy_1 小时前
基于SpringAI的在线考试系统-考试系统DDD(领域驱动设计)实现步骤详解
java·数据库·人工智能·spring boot
毕设源码-钟学长1 小时前
【开题答辩全过程】以 基于Java的运动器材销售网站为例,包含答辩的问题和答案
java·开发语言