Java解析Word模版,替换${}的值

hutllo工具包

  1. <!--Hutool Java工具包-->
  2. <dependency>
  3. <groupId>cn.hutool</groupId>
  4. <artifactId>hutool-all</artifactId>
  5. <version>4.5.7</version>
  6. </dependency>

 

一、创建一个存放参数的对象

  1. import io.swagger.annotations.ApiModelProperty;
  2. import lombok.Data;
  3. @Data
  4. public class WordParam {
  5.  
  6. @ApiModelProperty("编号")
  7. private String testNum;
  8.  
  9. @ApiModelProperty("描述")
  10. private String testDescription;
  11.  
  12. @ApiModelProperty("方案")
  13. private String testPlan;
  14.  
  15. @ApiModelProperty("机构")
  16. private String testOrg;
  17.  
  18. @ApiModelProperty("时间")
  19. private String testTime;
  20.  
  21. }

二、创建一个需要解析的word模版

三、解析模版

  1. public static void main(String[] args) throws IOException, InvocationTargetException, IllegalAccessException {
  2. WordParam wordParam = new WordParam();
  3. wordParam.setTestNum("20200821");
  4. wordParam.setTestDescription("描述测试");
  5. wordParam.setTestPlan("解决方案");
  6. wordParam.setTestOrg("测试机构");
  7. wordParam.setTestTime("2020年8月21日");
  8. // 模版位置
  9. File file = new File("F:\\Download\\0b890e20e2b911eab1d06b280e56848b.docx");
  10. InputStream inputStream = new FileInputStream(file);
  11. XWPFDocument document = new XWPFDocument(inputStream);
  12. // 获取整个文本对象
  13. List<XWPFParagraph> paragraphs = document.getParagraphs();
  14. // 存放匹配字段的值
  15. Map map = MapUtil.of(new String[][]{
  16. {"${编号}", "TestNum"},
  17. {"${描述}", "TestDescription"},
  18. {"${方案}", "TestPlan"},
  19. {"${机构}", "TestOrg"},
  20. {"${时间}", "TestTime"}
  21. });
  22. for (XWPFParagraph paragraph : paragraphs) {
  23. List<XWPFRun> runs = paragraph.getRuns();
  24. for (XWPFRun run : runs) {
  25. // 获取word中每一个段落的内容
  26. String runString = run.toString();
  27. // 正则匹配word要替换的内容
  28. Matcher m = Pattern.compile("\\$\\{(.*?)}").matcher(runString);
  29. if (m.find()) {
  30. log.info("输出doc中要替换的内容:{}", runString);
  31. for (Object key : map.keySet()) {
  32. if (runString.equals(key)) {
  33. Object param = map.get(key);
  34. String getParam = "get" + param.toString();
  35. Method method = ReflectUtil.getMethod(WordParam.class, getParam);
  36. Object o = method.invoke(wordParam);
  37. run.setText(o.toString(), 0);
  38. }
  39. }
  40. }
  41. }
  42. }
  43. FileOutputStream fileOutputStream = new FileOutputStream("D:/ExportExcelTest/wordTest.docx");
  44. document.write(fileOutputStream);
  45. document.close();
  46.  
  47. }

四、最后结果

posted on 2020-11-03 16:18  微笑点燃希望  阅读(3451)  评论(2编辑  收藏  举报
font=white