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

       }
   }
相关推荐
C+++Python20 分钟前
C++ 进阶学习完整指南
java·c++·学习
sparEE37 分钟前
c++值类别、右值引用和移动语义
开发语言·c++
zhangjw3439 分钟前
第11篇:Java Map集合详解,HashMap底层原理、哈希冲突、JDK1.8优化、遍历方式彻底吃透
java·开发语言·哈希算法
还得是你大哥1 小时前
Java互联网医院管理系统源码SpringBoot
java·spring boot·vue
阿维的博客日记1 小时前
怎么用ThreadLocal解决用户的登录上下文
java·juc
Dicky-_-zhang2 小时前
容器编排实战:Docker与Kubernetes对比选型与落地实践
java·jvm
benpaodeDD2 小时前
视频10,11,12,13——java程序的加载与执行,安装jdk
java·开发语言
一颗牙牙2 小时前
安装mmcv
开发语言·python·深度学习
大空大地20262 小时前
C#高级语法总结
开发语言·c#
ytttr8732 小时前
DSP 28335 CAN总线通信程序
开发语言·stm32·单片机