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

       }
   }
相关推荐
m0_56491492几秒前
Altium Designer,AD如何修改原理图右下角图纸标题栏?如何自定义标题栏?自定义原理图模版的使用方法
java·服务器·前端
飞升不如收破烂~几秒前
# Spring Boot 跨域请求未到达后端问题排查记录
java·spring boot·后端
AllData公司负责人1 分钟前
【亲测好用】数据集成管理能力演示
java·大数据·数据库·开源
brevity_souls3 分钟前
SQL Server 窗口函数简介
开发语言·javascript·数据库
阿蒙Amon6 分钟前
C#每日面试题-值传递和引用传递的区别
java·面试·c#
aloha_7897 分钟前
乐信面试准备
java·spring boot·python·面试·职场和发展·maven
火云洞红孩儿13 分钟前
零基础:100个小案例玩转Python软件开发!第六节:英语教学软件
开发语言·python
Knight_AL17 分钟前
Spring Boot 多模块项目中优雅实现自动配置(基于 AutoConfiguration.imports)
java·spring boot·mybatis
短剑重铸之日21 分钟前
《RocketMQ研读》面试篇
java·后端·面试·职场和发展·rocketmq
AI殉道师24 分钟前
FastScheduler:让 Python 定时任务变得优雅简单
开发语言·python