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();
-
-
}
四、最后結果