Java Word模板POI生成文件

使用 Apache POI 实现 Word 模板动态填充与文件生成

简介

在企业级 Java 应用中,经常需要根据模板动态生成 Word 文档(如合同、报告、通知等)。 Apache POI 是一个强大的 Java 库,支持读写 Microsoft Office 格式文件,其中 XWPF 模块用于处理 .docx 文件。

核心步骤

  1. 准备一个 .docx 模板文件,使用占位符(如 ${name}、${date})标记需替换内容。
  2. 使用 Java 读取该模板文件。
  3. 遍历文档中的段落和表格,替换占位符为实际数据。
  4. 将修改后的文档输出为新的 .docx 文件。

示例代码

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> data) 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, data);
            }

            // 替换表格中的占位符
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            replaceInParagraph(paragraph, data);
                        }
                    }
                }
            }

            doc.write(fos);
        }
    }

    private static void replaceInParagraph(XWPFParagraph paragraph, Map<String, String> data) {
        for (XWPFRun run : paragraph.getRuns()) {
            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);
            }
        }
    }
}

依赖配置(Maven)

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.4</version>
</dependency>

注意事项

更多功能More features
批量转换批量转换批量处理文件,支持docx/txt 降低AI率降低AI率用更自然的表达方式重写内容 改写建议改写建议看看同一句话还能怎么说