java freemarker动态替换word文档中占位符

1.使用map替换

public static  void createWord(Map<String,Object> dataMap, String templateName, ByteArrayOutputStream outputStream){
      try {
         //创建配置实例
         Configuration configuration = new Configuration();
         //设置编码
         configuration.setDefaultEncoding("UTF-8");

         //设置编码
         configuration.setDefaultEncoding("UTF-8");

         File exportTemplate = ResourceFinder.getResources("exportTemplate")[0].getFile();
         configuration.setDirectoryForTemplateLoading(exportTemplate);// 本地模板路径
         //获取模板
         Template template = configuration.getTemplate(templateName);
         Writer out = new OutputStreamWriter(outputStream);
         //生成文件
         template.process(dataMap, out);
         //关闭流
         out.flush();
         out.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

2.使用

public void exportDutyLog(String ownerId, LocalDate date, HttpServletResponse response) throws IOException {
      String fileName = "值班日志-".concat(date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))).concat(".docx");
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      HashMap<String, Object> stringMaps = Maps.newHashMap();
      try {
         process(ownerId, date, stringMaps);
      }
      catch(Exception e) {
         e.printStackTrace();
      }
      createWord(stringMaps,"dutylog.ftl",outputStream);
      response.setCharacterEncoding("utf-8");
      // 设置编码格式
      response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
      ServletOutputStream servletOutputStream = response.getOutputStream();
      servletOutputStream.write(outputStream.toByteArray());
   }

3.使用时需要将word导出为xml,修改错乱的占位符位置,方法调用即可成功

4.依赖

compile group: 'org.freemarker', name: 'freemarker', version: '2.3.28'
posted @ 2022-04-21 15:40  海的味道  阅读(933)  评论(0编辑  收藏  举报