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

       }
   }
相关推荐
AI玫瑰助手17 小时前
Python函数:函数的返回值(return)与多值返回
开发语言·python·信息可视化
大湿兄啊啊啊17 小时前
MID360S调试
java·服务器·前端
花果山~~程序猿17 小时前
快速认识python项目的虚拟环境
开发语言·python
.Cnn17 小时前
Maven进阶知识点
java·maven
basketball61617 小时前
Go语言从入门到进阶:8. 接口
开发语言·后端·golang
布朗克16817 小时前
11 面向对象思想入门
java·对象
gCode Teacher 格码致知17 小时前
Python教学:字符编码的四种环境-由Deepseek产生
开发语言·python
拽着尾巴的鱼儿17 小时前
lombok.RequiredArgsConstructor bean 注入
java·lombok
铁链鞭策大师17 小时前
JavaEE之多线程
java·开发语言·java-ee
摇滚侠17 小时前
Maven 入门+高深 jar 包冲突 167-171
java·maven·jar