掌握Apache POI技术,实现高效、灵活的Word文档自动化生成
Apache POI是Apache软件基金会的开源项目,提供Java API用于操作Microsoft Office格式文件。其中,XWPF组件专门用于处理Word文档(.docx格式)。
通过POI,开发者可以在Java应用中创建、修改和读取Word文档,特别适合生成报表、合同、证书等需要模板化的文档。
使用模板生成Word文件的核心思路是:
${name}, ${date})<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.4</version>
</dependency>
设计Word文档,使用${变量名}作为占位符,如:${customerName}, ${orderDate}
import org.apache.poi.xwpf.usermodel.*;
public class WordGenerator {
public void generateFromTemplate(String templatePath, String outputPath, Map<String, String> data)
throws Exception {
// 读取模板
XWPFDocument doc = new XWPFDocument(OPCPackage.open(templatePath));
// 替换段落中的占位符
for (XWPFParagraph p : doc.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun run : runs) {
String text = run.getText(0);
if (text != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
text = text.replace("${" + entry.getKey() + "}", entry.getValue());
}
run.setText(text, 0);
}
}
}
}
// 处理表格(可选)
for (XWPFTable table : doc.getTables()) {
// 遍历表格进行替换...
}
// 保存文件
FileOutputStream out = new FileOutputStream(outputPath);
doc.write(out);
out.close();
doc.close();
}
}
XWPFRun.addPicture()方法插入二进制图片数据这些功能使POI非常适合生成复杂的业务文档,如财务报表、法律合同、个性化证书等。
该技术广泛应用于: