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

       }
   }
相关推荐
念何架构之路14 小时前
Go Socket编程
开发语言·后端·golang
feifeigo12314 小时前
基于无迹变换的电网概率潮流分析 MATLAB 实现
开发语言·算法·matlab
时空系14 小时前
第13篇:综合实战——制作我的小游戏 Rust中文编程
开发语言·后端·rust
CoderCodingNo14 小时前
【信奥业余科普】C++ 的奇妙之旅 | 19:内存的门牌号——地址与指针的设计原理
开发语言·c++
咖啡八杯14 小时前
GoF设计模式——单例模式
java
0xDevNull14 小时前
JDK多版本切换安装与配置
java·后端
流年似水~14 小时前
Java新手5分钟接AI:Spring AI Alibaba实战
java·人工智能·spring
DarkAthena14 小时前
【YaShanDB】给YaShanDB开发R2DBC驱动
java·yashandb·r2dbc
@insist12315 小时前
信息安全工程师-物理隔离技术基础核心考点解析
开发语言·网络·安全·软考·信息安全工程师·软件水平考试