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

       }
   }
相关推荐
NGC_661117 分钟前
二分查找算法
java·javascript·算法
海兰33 分钟前
ES9.x 银行场景:银行卡可疑交易风控工作流示例
java·elasticsearch·搜索引擎
勇往直前plus38 分钟前
深入理解 Python 内存模型:模块、类、对象的存储与运行机制
开发语言·python
Drifter_yh1 小时前
「JVM」 深入剖析 JVM 内存结构:从底层原理到线上排查
java·jvm
派大星-?1 小时前
自动化测试五模块一框架(下)
开发语言·python
莫寒清1 小时前
Java 线程池详解
java·面试
三无少女指南2 小时前
开发者环境配置:用 Ollama 实现本地大模型部署(附下载慢的解决方案
c语言·开发语言·数据库·ubuntu
廋到被风吹走2 小时前
安全防护深度解析:敏感信息加密、密码哈希与密钥管理实战
java
biyezuopinvip2 小时前
基于Spring Boot的投资理财系统设计与实现(毕业论文)
java·spring boot·vue·毕业设计·论文·毕业论文·投资理财系统设计与实现
iAkuya2 小时前
(leetcode)力扣100 75前K个高频元素(堆)
java·算法·leetcode