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

       }
   }
相关推荐
大大。3 分钟前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
nc_kai5 分钟前
Flutter 之 每日翻译 PreferredSizeWidget
java·前端·flutter
shootero@126.com13 分钟前
R语言开发记录,一
开发语言·r语言
Codebee15 分钟前
OneCode:AI时代的先锋——注解驱动技术引领开发范式变革
java
勤奋的知更鸟16 分钟前
Java 编程之状态模式
java·开发语言·状态模式
沐知全栈开发25 分钟前
R 列表:深入解析与高效应用
开发语言
架构个驾驾26 分钟前
深入浅出MyBatis-Plus实战指南
java
爱喝茶的小茶26 分钟前
周赛98补题
开发语言·c++·算法
SimonKing30 分钟前
解锁万能文件内容分析工具:Apache Tika
java·后端·程序员
Whoisshutiao1 小时前
Python网安-zip文件暴力破解(仅供学习)
开发语言·python·网络安全