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

       }
   }
相关推荐
huwei853几秒前
Q打印表格内容类
开发语言·qt
一嘴一个橘子2 分钟前
spring-aop 的 基础使用 -3 - 切点表达式 的提取、复用
java
Re_zero4 分钟前
Java新手避坑:为什么我劝你放弃 scanner.nextInt()?
java
oioihoii10 分钟前
构建高并发AI服务网关:C++与gRPC的工程实践
开发语言·c++·人工智能
X***078825 分钟前
从底层逻辑到工程实践,深入理解C语言在计算机世界中的核心地位与持久价值
c语言·开发语言
晚枫歌F30 分钟前
io_uring的介绍和实现
开发语言·php
Good_Starry38 分钟前
Java——反射
java
时光追逐者41 分钟前
TIOBE 公布 C# 是 2025 年度编程语言
开发语言·c#·.net·.net core·tiobe
花归去44 分钟前
echarts 柱状图曲线图
开发语言·前端·javascript
又是忙碌的一天1 小时前
SpringBoot 创建及登录、拦截器
java·spring boot·后端