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

       }
   }
相关推荐
独自归家的兔28 分钟前
OCPP 1.6 协议详解:GetLocalListVersion 获取本地列表版本指令
java·后端·物联网·spring·ocpp1.6
XMYX-01 小时前
28 - Go JSON 数据操作
开发语言·golang·json
三*一1 小时前
Mapbox GL JS 自研面要素整形工具开发实录
开发语言·javascript·arcgis·ecmascript
Apache RocketMQ2 小时前
RocketMQ源码解析——秒级定时消息介绍
java·云原生·消息队列·rocketmq·java-rocketmq
超级小星星2 小时前
C 语言结构体内存对齐深度解析:从概念到实战
c语言·开发语言
狮子座明仔2 小时前
AgentSPEX:当 Agent 框架开始把“控制流“从 Python 里抠出来
开发语言·python
xiaoming00182 小时前
JAVA项目打包部署运维全流程(多服务、批量)
java·linux·运维
拾-光2 小时前
【Git】命令大全:从入门到高手,100 个最常用命令速查(2026 版)
java·大数据·人工智能·git·python·elasticsearch·设计模式
笨笨饿2 小时前
74_SysTick滴答定时器中断
c语言·开发语言·人工智能·单片机·嵌入式硬件·算法·学习方法
无人不xiao2 小时前
springBoot 实现 接口进度条
java·spring boot·后端