Java解析Word模版,替换${}的值
hutllo工具包
-
<!--Hutool Java工具包-->
-
<dependency>
-
<groupId>cn.hutool</groupId>
-
<artifactId>hutool-all</artifactId>
-
<version>4.5.7</version>
-
</dependency>
一、创建一个存放参数的对象
-
import io.swagger.annotations.ApiModelProperty;
-
import lombok.Data;
-
-
public class WordParam {
-
-
-
private String testNum;
-
-
-
private String testDescription;
-
-
-
private String testPlan;
-
-
-
private String testOrg;
-
-
-
private String testTime;
-
-
}
二、创建一个需要解析的word模版
三、解析模版
-
public static void main(String[] args) throws IOException, InvocationTargetException, IllegalAccessException {
-
WordParam wordParam = new WordParam();
-
wordParam.setTestNum("20200821");
-
wordParam.setTestDescription("描述测试");
-
wordParam.setTestPlan("解决方案");
-
wordParam.setTestOrg("测试机构");
-
wordParam.setTestTime("2020年8月21日");
-
// 模版位置
-
File file = new File("F:\\Download\\0b890e20e2b911eab1d06b280e56848b.docx");
-
InputStream inputStream = new FileInputStream(file);
-
XWPFDocument document = new XWPFDocument(inputStream);
-
// 获取整个文本对象
-
List<XWPFParagraph> paragraphs = document.getParagraphs();
-
// 存放匹配字段的值
-
Map map = MapUtil.of(new String[][]{
-
{"${编号}", "TestNum"},
-
{"${描述}", "TestDescription"},
-
{"${方案}", "TestPlan"},
-
{"${机构}", "TestOrg"},
-
{"${时间}", "TestTime"}
-
});
-
for (XWPFParagraph paragraph : paragraphs) {
-
List<XWPFRun> runs = paragraph.getRuns();
-
for (XWPFRun run : runs) {
-
// 获取word中每一个段落的内容
-
String runString = run.toString();
-
// 正则匹配word要替换的内容
-
Matcher m = Pattern.compile("\\$\\{(.*?)}").matcher(runString);
-
if (m.find()) {
-
log.info("输出doc中要替换的内容:{}", runString);
-
for (Object key : map.keySet()) {
-
if (runString.equals(key)) {
-
Object param = map.get(key);
-
String getParam = "get" + param.toString();
-
Method method = ReflectUtil.getMethod(WordParam.class, getParam);
-
Object o = method.invoke(wordParam);
-
run.setText(o.toString(), 0);
-
}
-
}
-
}
-
}
-
}
-
FileOutputStream fileOutputStream = new FileOutputStream("D:/ExportExcelTest/wordTest.docx");
-
document.write(fileOutputStream);
-
document.close();
-
-
}
四、最后结果