感谢大萌音音’s B站视频的分享, 如有不懂, 可以去看这个视频
1. poi 依赖2. java 替换word模板流程org.apache.poi poi-ooxml 3.17 org.apache.poi poi 3.17
- word中主要由两部分组合而成: 段落和表格
- 判断需要被替换的部分是在段落中还是表格中
- 假设在表格中, 则遍历所有的单元格内容, 找到并修改
- 在将修改后的覆盖原内容, 最后输出即可
public class ReplaceWordContent {
public static void main(String[] args) {
FileInputStream inputStream = null;
OutputStream out = null;
XWPFDocument document = null;
try {
inputStream = new FileInputStream("C:\Users\via\Desktop\TEST.docx");
out = new FileOutputStream("C:\Users\via\Desktop\TEST1.docx");
document = new XWPFDocument(inputStream);
List tables = document.getTables();
Map map = new HashMap<>();
map.put("${name}", "张三");
map.put("${age}", "15");
map.put("${gender}", "男");
map.put("${position}", "总经理");
replaceWordContent(document, map);
document.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(document);
}
}
public static void replaceWordContent(XWPFDocument document, Map relationMap)
{
List tables = document.getTables();
// 获取所有表格
for (XWPFTable table : tables) {
// 获取表格的每一行数据
for (XWPFTableRow row : table.getRows()) {
// 获取表格的每一个单元格
for (XWPFTableCell cell : row.getTableCells()) {
String text = cell.getText();
// 移除操作, 因为poi底层对word是追加操作, 如果不移除, 会在原内容是拼接,
cell.removeParagraph(0);
// 再新增一个格式
XWPFParagraph paragraph = cell.addParagraph();
// 设置行间距
paragraph.setSpacingBetween(1);
// 替换后的新值
String newText = replaceCellContent(text, relationMap);
// 将值放入单元格
cell.setText(newText);
}
}
}
}
public static String replaceCellContent(String cellContent, Map relationMap)
{
if (isEmpty(cellContent))
{
return "";
}
for (Map.Entry entry : relationMap.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
if (cellContent.contains(k))
{
cellContent = cellContent.replace(k, v);
return cellContent;
}
}
return "";
}
public static boolean isEmpty(String str)
{
if (null == str || str.length() == 0)
{
return true;
}
return false;
}
}



