什么是 Apache POI?
Apache POI 是一个开源的 Java API,用于读写 Microsoft Office 文档(如 Word、Excel、PowerPoint)。其中,XWPF 组件专门用于处理 .docx 格式的 Word 文档。
为什么使用 Word 模板?
在实际开发中,常常需要根据业务数据动态填充 Word 文档。通过预先设计好格式的 Word 模板,再用 Java 程序替换占位符(如 ${name}、${date}),可以高效生成标准化文档,适用于合同、报告、证书等场景。
基础代码示例
以下是一个使用 POI 替换 Word 模板中占位符的简单示例:
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.util.Map;
public class WordTemplateGenerator {
public static void generateWord(String templatePath, String outputPath, Map<String, String> replacements) throws Exception {
try (FileInputStream fis = new FileInputStream(templatePath);
FileOutputStream fos = new FileOutputStream(outputPath)) {
XWPFDocument doc = new XWPFDocument(fis);
// 替换段落中的文本
for (XWPFParagraph paragraph : doc.getParagraphs()) {
replaceInParagraph(paragraph, replacements);
}
// 替换表格中的文本
for (XWPFTable table : doc.getTables()) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
replaceInParagraph(paragraph, replacements);
}
}
}
}
doc.write(fos);
}
}
private static void replaceInParagraph(XWPFParagraph paragraph, Map<String, String> replacements) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
if (text != null) {
for (Map.Entry<String, String> entry : replacements.entrySet()) {
text = text.replace("${" + entry.getKey() + "}", entry.getValue());
}
run.setText(text, 0);
}
}
}
}
依赖配置(Maven)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.4</version>
</dependency>
注意事项
- 确保模板为
.docx格式(非旧版 .doc) - 复杂样式(如合并单元格、图片)需额外处理
- 中文字符建议使用 UTF-8 编码
- 对于高性能需求,可考虑缓存模板或使用线程安全方案