[原创] Java poi替换模板
2020-06-23 本文已影响0人
韩朝阳
设置替换内容Map(也可以通过反射根据字段名从实体类中获取字段值)
// data为实体类
HashMap<String, String> valueMap = new HashMap<>();
valueMap.put("#{name}", data.getName());
valueMap.put("#{unit}", data.getUnit());
valueMap.put("#{post}", data.getPost());
valueMap.put("#{phone}", data.getPhone());
设置提取占位符的正则表达式
// 该表达式可提取#{xxx}占位符
private static final String REG_EX = "#\\{.*?\\}";
遍历模板表格替换
// xxx.docx为模板路径
XWPFDocument document = new XWPFDocument(new FileInputStream(new File("xxx.docx")));
// 表格序号,从0开始
int n = 0;
XWPFTable table = document.getTables().get(n);
List<XWPFTableRow> rows = table.getRows();
for (int r = 0; r < rows.size(); r++) {
XWPFTableRow row = rows.get(r);
List<XWPFTableCell> tableCells = row.getTableCells();
for (int c = 0; c < tableCells.size(); c++) {
XWPFTableCell cell = tableCells.get(c);
XWPFParagraph paragraph = cell.getParagraphs().get(0);
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String placeholder = matcher.group();
text = text.replace(placeholder, valueMap.get(placeholder));
run.setText(text, 0);
}
}
}
}
try {
// yyy.docx为文件输出路径
document.write(new FileOutputStream(new File("yyy.docx")));
} catch (IOException e) {
e.printStackTrace();
}
if (document != null) {
try {
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}