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

       }
   }
相关推荐
The_SkyUzi4 分钟前
【无标题】
java·maven
dllmayday13 分钟前
Qt/QML + C++ 双向数据绑定(MVVM 模式的几种常用方法(ChatGPT)
开发语言·c++·qt
han_hanker22 分钟前
统一拦截异常 @RestControllerAdvice
java·开发语言·数据库
liu****24 分钟前
一.脚手架介绍以及部分工具使用
开发语言·数据结构·c++·手脚架开发
资深web全栈开发33 分钟前
深入理解 Google Wire:Go 语言的编译时依赖注入框架
开发语言·后端·golang
忘记92637 分钟前
什么是spring boot
java·spring boot·后端
ohoy38 分钟前
EasyPoi 数据脱敏
开发语言·python·excel
Hello World呀40 分钟前
Java实现手机号和身份证号脱敏工具类
java·开发语言
曹牧42 分钟前
Java:serialVersionUID
java·开发语言
ekprada1 小时前
DAY36 复习日
开发语言·python·机器学习