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

       }
   }
相关推荐
笃行客从不躺平12 分钟前
线程池原理复习
java·开发语言
weixin_4487717216 分钟前
SpringMVC执行流程源码分析之二
java
A尘埃22 分钟前
大模型应用python+Java后端+Vue前端的整合
java·前端·python
A尘埃26 分钟前
LLM大模型评估攻略
开发语言·python
littlepeanut.top27 分钟前
C++中将FlatBuffers序列化为JSON
开发语言·c++·json·flatbuffers
一晌小贪欢1 小时前
【Python办公】处理 CSV和Excel 文件操作指南
开发语言·python·excel·excel操作·python办公·csv操作
清风与日月1 小时前
c# 集成激光雷达(以思岚A1为例)
开发语言·c#
皮皮林5511 小时前
MinIO 不再“开放”,RustFS 能否成为更优选择?
java
多喝开水少熬夜1 小时前
树与图的深度和广度优先遍历-java实现邻接表存储
java·深度优先·宽度优先
是苏浙1 小时前
零基础入门C语言之贪吃蛇的实现
c语言·开发语言·数据结构