import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TemplateUtils {
public static void replacePlaceholder(XWPFDocument xwpfDocument, Map<String, String> dataMap) {
for (XWPFParagraph paragraph : xwpfDocument.getParagraphs()) {
replacePlaceholder(paragraph, dataMap);
}
}
/**
* 填充段落中的占位符
*/
public static void replacePlaceholder(XWPFParagraph paragraph, Map<String, String> dataMap) {
if (paragraph.getText().contains("$")) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.text();
System.out.println(text);
for (String key : dataMap.keySet()) {
String placeHolder = "${" + key + "}";
if (text.contains(placeHolder)) {
text = text.replace(placeHolder, dataMap.get(key));
run.setText(text, 0);
}
}
}
}
}
/**
* 填充表格中的占位符
*/
public static void replacePlaceholderInTable(XWPFTable table, Map<String, String> dataMap) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell tableCell : row.getTableCells()) {
for (XWPFParagraph paragraph : tableCell.getParagraphs()) {
replacePlaceholder(paragraph, dataMap);
}
}
}
}
public static void main(String[] args) throws Exception {
// 准备数据
Map<String, String> dataMap = prepareData();
// 加载文件
String docPath = "src/main/resources/doc/信息表.docx";
FileInputStream fileInputStream = new FileInputStream(docPath);
XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);
// 填充段落
List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
System.out.println(paragraphs.size());
for (XWPFParagraph paragraph : paragraphs) {
replacePlaceholder(paragraph, dataMap);
}
// 填充表格
// 表格的每个单元格,也是段落
List<XWPFTable> tables = xwpfDocument.getTables();
System.out.println(tables.size());
for (XWPFTable table : tables) {
replacePlaceholderInTable(table, dataMap);
}
FileOutputStream fileOutputStream = new FileOutputStream("src/main/resources/doc/out.docx");
xwpfDocument.write(fileOutputStream);
fileOutputStream.close();
fileInputStream.close();
xwpfDocument.close();
}
private static Map<String, String> prepareData() {
Map<String, String> dataMap = new HashMap<>();
dataMap.put("author", "荧");
dataMap.put("createTime", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
dataMap.put("name", "Tom");
dataMap.put("age", "14");
dataMap.put("gender", "男");
dataMap.put("birth", "1940-01-01");
dataMap.put("address", "北京");
dataMap.put("workAddress", "上海");
dataMap.put("mobile", "6570123");
dataMap.put("phone", "13478965412");
dataMap.put("petName", "jerry");
dataMap.put("petAge", "10");
dataMap.put("petGender", "男");
dataMap.put("petBirth", "1940-01-01");
return dataMap;
}
}