- 引入Apache POI依赖
- 制作word模板
- 加载word模板,读取word模板的内容,替换占位符内容
- 将修改后文档另存为
一、基础示例
1. 引入依赖
在POM文件中引入相关依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.3</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency>2. 制作模板
新建一个word文档,需要动态替换的位置使用占位符,后面匹配到该占位符将数据填充到该位置即可。对于动态表格(项次条数不确定),在表格的第一行使用占位符 ${dynamicTable} 标记,表明该表格是动态表格,后面循环创建行并插入数据。
3.读取模板
1. 通过 XWPFDocument 加载模板文件
// 读取文件 InputStream is = new FileInputStream("这里填模板位置/inFile.docx"); XWPFDocument doc = new XWPFDocument(is);2. 替换文本内容
遍历段落替换占位符
for (XWPFParagraph paragraph : doc.getParagraphs()) { String