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

       }
   }
相关推荐
Javatutouhouduan4 分钟前
阿里Java面试核心讲(2027最新版)
java·spring boot·mybatis·java面试·后端开发·java程序员·java八股文
weixin_307779138 分钟前
Git中获取一个目录下所有文件的最后修改人的邮箱
开发语言·git·算法
简 洁 冬冬1 小时前
深入理解Result与枚举的分工-外壳花名册与协作全链
java·枚举
一起学安全技术1 小时前
Java栈Agent开发 03|Spring AI(二):Tool Calling、MCP 与结构化输出
java·人工智能·spring·spring ai·结构化输出·mcp·tool calling
源码_空间1 小时前
基于Springboot的在线错题本与复习计划系统(源码+文档)
java·spring boot·后端
Rain的Java大神之路1 小时前
别再用“延迟双删”赌一致性:Canal + RocketMQ + Redis 的工业级缓存失效链路,以及 MySQL 分库分表前必须算清的那笔账
java·后端·面试
我命由我123451 小时前
Android Gradle - Android Gradle 配置
android·java·linux·java-ee·kotlin·android studio·android-studio
himobrinehacken1 小时前
HackMyVM靶机Yulian
java·spring boot·后端
香蕉大香蕉(06敬畏市场)1 小时前
事务隔离级别、MVCC 与锁:一条线串起来
java·服务器·数据库·人工智能·面试·博客
CoderYanger1 小时前
Java EE 进阶:16. Spring原理(第一弹)
java·服务器·数据库·后端·spring·java-ee·github