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

       }
   }
相关推荐
做一个快乐的小傻瓜4 分钟前
ZYNQ DEV套件引脚约束
java·linux·运维
CoderYanger5 分钟前
Java EE:6.网络编程套接字(第二弹)
java·网络·程序人生·面试·职场和发展·java-ee·学习方法
devilnumber5 分钟前
Java Lambda 表达式 200 条常见问题、坑点、易错点、规范清单
java·开发语言
极客先躯7 分钟前
高级java每日一道面试题-2026年02月12日-实战篇[Docker]-什么是容器的 Seccomp 配置?如何自定义?
java·运维·分布式·docker·容器·自动化·文件
大大杰哥9 分钟前
Vue2学习(3)--组件中的通信方式/组件之间的交互
java·前端·javascript
zzz_23689 分钟前
【Java基础】二叉树遍历与红黑树的完美平衡艺术——从递归崩溃到自平衡的硬核拆解
java·开发语言
程序员zgh9 分钟前
C++ 万能引用与完美转发
c语言·开发语言·c++·经验分享·学习
斯内普吖11 分钟前
(开源)高校素拓分管理系统小程序实战指南 基于 Java + SpringBoot + uni-app + Vue + MySQL
java·spring boot·mysql·小程序·uni-app·开源
Chris-zz14 分钟前
lua流程控制
开发语言·lua
yong999017 分钟前
IMU 扩展卡尔曼滤波(EKF)姿态估计 — MATLAB 实现
开发语言·matlab