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

       }
   }
相关推荐
HAPPY酷3 分钟前
C++ 成员指针(Pointer to Member)完全指南
java·c++·算法
Sunsets_Red9 分钟前
浅谈随机化与模拟退火
java·c语言·c++·python·算法·c#·信息学竞赛
星火开发设计28 分钟前
模板参数:类型参数与非类型参数的区别
java·开发语言·前端·数据库·c++·算法
忘梓.38 分钟前
二叉搜索树·极速分拣篇」:用C++怒肝《双截棍》分拣算法,暴打节点删除Boss战!
开发语言·c++·算法
星辰徐哥38 分钟前
Java数组的定义、操作与应用场景
java·开发语言
Aileen_0v039 分钟前
【数据结构中链表常用的方法实现过程】
java·开发语言·数据结构·算法·链表·动态规划·csdn开发云
草莓熊Lotso1 小时前
《算法闯关指南:优选算法--滑动窗口》--15.串联所有单词的子串,16.最小覆盖子串
开发语言·c++·人工智能·算法
Andy Dennis1 小时前
一文认识Java常见集合
java·开发语言
kyle~2 小时前
Python---Flask 轻量级Web框架
开发语言·python·flask
云深处@2 小时前
【C++11】特殊类&&单例模式
开发语言·c++