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'


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM