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

       }
   }
相关推荐
nice_lcj52035 分钟前
Spring 事务:声明式事务怎么生效
java·spring·面试·事务·transactional·传播机制
沐知全栈开发44 分钟前
基于Flask的班级信息与班务管理系统设计与实现-毕业设计
java·flask·课程设计
RobinXYuan1 小时前
【Java 字节码探秘】04 总览:索引空间与 17 种 cp_info
java·jvm·源码阅读
vx-程序开发1 小时前
【毕设分享】05253基于Spring+Boot的作业提交与管理系统的设计与实现
java·spring boot·后端·spring·源码·课程设计·大作业
Rain的Java大神之路2 小时前
把 ThreadLocal 换成 ScopedValue 后,请求上下文为什么在子线程里"消失"了?三个边界 + 完整迁移指南(JDK 25)
java·后端·面试
inferno2 小时前
Java正则表达式学习笔记
java·笔记·学习·正则表达式
布莱克6052 小时前
Swift 可选链详解:从语法到实战
开发语言·ios·swift·可选链
会编程的吕洞宾3 小时前
JVM频繁Full GC排查实战_后端定位与调优
java·经验分享·后端
布莱克6053 小时前
Swift 类型转换详解:从基础语法到实战技巧
开发语言·ios·swift·类型转换
木井巳3 小时前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法