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

       }
   }
相关推荐
sugar椰子皮7 分钟前
【爬虫框架-5】实现一下之前的思路
开发语言·爬虫·python
沈询-阿里8 分钟前
AI Agent系列 - 1 什么是 ReAct Agent?
开发语言·javascript·ecmascript
沐知全栈开发12 分钟前
jEasyUI 创建异步树形菜单
开发语言
凌云若寒14 分钟前
半导体标签打印的核心痛点分析
java
灰乌鸦乌卡15 分钟前
泛微OA集成档案信息包生成
java
2301_8035545215 分钟前
利用信号完成这个联动需求
java·开发语言
世转神风-16 分钟前
qt-弹框提示-界面提醒
开发语言·qt·策略模式
5008417 分钟前
鸿蒙 Flutter 超级终端适配:多设备流转与状态无缝迁移
java·人工智能·flutter·华为·性能优化·wpf
codealy17 分钟前
Spring 事务失效的八大场景深度解析
java·spring boot·后端·spring
计算衎17 分钟前
基于python的FastAPI框架目录结构介绍、开发思路和标准开发模板总结
开发语言·python·fastapi