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

       }
   }
相关推荐
少控科技几秒前
小数典应用:农场环境数据采集监控
开发语言·windows·c#
叶小鸡3 分钟前
Java 篇-项目实战-天机学堂(从0到1)-day7
java·开发语言
原来是猿3 分钟前
Linux线程同步与互斥(五):线程池的全面实现
linux·服务器·开发语言
何中应4 分钟前
记录一次Jenkins构建任务的坑
java·servlet·jenkins
eqwaak06 分钟前
PyTorch入门:10分钟搭建首个神经网络
开发语言·人工智能·pytorch·python
雪碧聊技术7 分钟前
上午题_计算机系统
java·开发语言
纤纡.8 分钟前
解锁 Python 实用编程技巧:线程、视觉识别、正则匹配与装饰器实战
开发语言·python·深度学习·opencv
t***54413 分钟前
如何在Dev-C++中配置Clang编译器
开发语言·c++
逆境不可逃14 分钟前
一篇速通RabbitMQ (从入门到生产实战:核心原理、高级特性与 Spring Boot 集成全解)
开发语言·后端·ruby
yuanpan18 分钟前
Python Pandas 库入门:介绍与基本使用教程
开发语言·python·pandas