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

       }
   }
相关推荐
雨夜之寂1 分钟前
第一章-第三节-Java开发环境配置
java·后端
郑清9 分钟前
Spring AI Alibaba 10分钟快速入门
java·人工智能·后端·ai·1024程序员节·springaialibaba
zl97989918 分钟前
SpringBoot-Web开发之数据响应
java·spring boot·后端
旷野说26 分钟前
Spring Boot 1.x、2.x 3.x区别汇总
java·spring·tomcat·1024程序员节
没有bug.的程序员34 分钟前
Spring Boot 起步:自动装配的魔法
java·开发语言·spring boot·后端·spring·1024程序员节
Hero | 柒36 分钟前
设计模式之建造者模式
java·设计模式·1024程序员节
CodeLongBear40 分钟前
帝可得智能售货机系统实战Day1:从环境搭建到区域管理功能落地 (1)
java·1024程序员节·ai + 若依框架
235161 小时前
【MySQL】慢查寻的发现和解决优化(思维导图版)
java·后端·sql·mysql·职场和发展·数据库开发·数据库架构
面向星辰1 小时前
windows配置hadoop环境
java·开发语言
小超嵌入式笔记1 小时前
【Keil5教程及技巧】耗时一周精心整理万字全网最全Keil5(MDK-ARM)功能详细介绍【建议收藏-细细品尝】
java·数据库·mongodb