需求背景:因项目需要无法使用poi-tl包利用{{}}定位的方式向word模板的指定位置填写信息
解决方法:现利用替换占位字段的方式,在要替换的地方前后都插入书签
示例word:
在需要替换填写内容的地方放置占位标识并在该标识前后添加书签
代码示例:
/**
* @author YongXin
* @date Created in 2022/7/18 20:57
*/
public class InsertWordTest {
public static void main(String[] args) throws IOException {
Map<String,String> map = new HashMap<>();
map.put("mj","内部");
map.put("dept","办公室");
map.put("b","小明,小红");
map.put("h","董事会");
insertAndOutFile("C:/Users/96522/Desktop/template.docx","C:/Users/96522/Desktop/out.docx",map);
}
/**
*将word中某些标签替换成指定的值,并生成一个新的word文档。
* @param templateFilePath word模板文件路径
* @param outFilePath 填充后输出文件路径
* @param map key:word中的占位标签,value对应标签要替换的值。
* @throws IOException
*/
public static void insertAndOutFile(String templateFilePath, String outFilePath, Map<String,String> map) throws IOException {
//准备工作,生成docx对象
String templatePath=templateFilePath;
InputStream is=new FileInputStream(templatePath);
XWPFDocument docx=new XWPFDocument(is);
//获取表格
List<XWPFTable> tables=docx.getTables();
//定位到第一个表格
XWPFTable table=tables.get(0);
//遍历该表格所有的行
for(int i=0;i<table.getRows().size();i++) {
XWPFTableRow row=table.getRow(i);
//遍历该行所有的列
for(int j=0;j<row.getTableCells().size();j++) {
XWPFTableCell cell=row.getTableCells().get(j);
//获取该格子里所有的段
List<XWPFParagraph> paragraphs=cell.getParagraphs();
for(XWPFParagraph p:paragraphs) {
//遍历该格子里的段
List<XWPFRun> runs=p.getRuns();
for(XWPFRun run:runs) {
//遍历该段里的所有文本
String str=run.toString();
//如果该段文本包含map中的key,则替换为map中的value值。
Set<String> keySet = map.keySet();
for(String key:keySet){
if(str.trim().equals(key)){
//替换该文本0位置的数据。
run.setText(map.get(key),0);
}
}
}
}
}
}
//输出
OutputStream os=new FileOutputStream(outFilePath);
docx.write(os);
is.close();
os.close();
}
}
依赖:
<dependencies>
<!-- word工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
</dependencies>
结果: