使用Freemarker输出word文档到浏览器与本地

一、使用模板引擎至少需要四步走:

  1.定义模板引擎
  2.创建数据模型
  3.填充数据到模板中
  4.输出文档

二:

  1、定义模板: 创建word文档,另存xml 文件(需要注意,存为 2003xml 文件,要不以后生成的word可能会出现office打不开的情况)

    

  2、 直接打开 格式会特变乱,此时需要格式化一下,可直接在线进行格式化  https://tool.oschina.net/codeformat/xml

  3、填充占位符,具体参考 ftl 语法 https://www.cnblogs.com/wongzzh/p/15137124.html

    包括  集合 Map  图片 

   4、变量处理完成,将后缀名改成 ftl,放到项目 templates目录下

三:代码处理

  1、引入依赖

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.30</version>
</dependency>

  2、输出到浏览器下载

    @GetMapping("/XXX")
    @ResponseBody
    public void print(HttpServletResponse response,@PathVariable("userId") String userId) throws IOException, Exception {
        
          //读取封装好的业务数据
        String content = exportFile(XXX);

        InputStream inputStream = IOUtils.toInputStream(content);
        ServletOutputStream out = null;
        try {
        
            //输出文件
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream;charset=UTF-8");
            //response.setHeader("Content-Disposition", "attachment;filename=" + "文件名"+".doc");
            response.setHeader("Content-Disposition", 
"attachment;filename=".concat(String.valueOf(URLEncoder.encode("文件名", "UTF-8")+ ".doc"))); out = response.getOutputStream(); byte[] buffer = new byte[1024]; // 缓冲区 int bytesToRead = -1; // 通过循环将读入的Word文件的内容输出到浏览器中 while((bytesToRead = inputStream.read(buffer)) != -1) { out.write(buffer, 0, bytesToRead); } }catch (Exception e){ log.error("导出Excel异常{}", e.getMessage()); throw new BusinessException("导出word失败,请联系网站管理员!"); }finally { out.flush(); out.close(); inputStream.close(); } } public String exportFile(HrStaffInfo staffInfo ) throws Exception{ //业务代码    String XXX = "姓名";
Map<String, Object> data = new HashMap<>();      //将业务数据放到 map中
data.put("name", XXX);
//创建配置类 Configuration configuration = new Configuration(Configuration.getVersion()); String classPath = this.getClass().getResource("/").getPath(); configuration.setDirectoryForTemplateLoading(new File(classPath+"templates/")); //获取模板文件 Template template = configuration.getTemplate("模板文件名.ftl"); String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, data); return content; }

   3、直接输出到本地

  @GetMapping("/XXX")
    @ResponseBody
    public TableDataInfo list(@PathVariable("userId") Long userId, HttpServletResponse response) throws Exception {

        //同上
        String content = exportFile(staffInfo);
        try {
            InputStream inputStream1 = IOUtils.toInputStream(content);
            //定义输出路径即可,其他代码与输出到浏览器保持一致
            FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.doc"));
            int copy = IOUtils.copy(inputStream1, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream1.close();
        } catch (Exception e) {
            logger.error("异常", e);
            throw new BaseException("XXX");
  }

参考:https://blog.csdn.net/Marion158/article/details/105261354

原文地址:https://www.cnblogs.com/wongzzh/p/15137839.html