使用Apache POI创建Word文档完全指南
使用Apache POI创建Word文档完全指南
Apache POI是Java中处理Microsoft Office文档的开源库,支持Word、Excel、PowerPoint等格式。本文将重点介绍如何使用POI创建Word文档(.docx),适合初学者和进阶开发者。
环境配置
首先在项目中引入POI依赖(Maven示例):
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>如果涉及图片,还需添加poi-scratchpad模块。
基本创建步骤
- 创建文档对象:
XWPFDocument document = new XWPFDocument(); - 创建段落:
XWPFParagraph paragraph = document.createParagraph();并设置对齐、缩进等。 - 添加文本:通过
XWPFRun run = paragraph.createRun();设置字体、大小、颜色等。 - 保存文档:
document.write(new FileOutputStream("demo.docx"));
示例代码
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileOutputStream;
public class CreateWord {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p1 = doc.createParagraph();
p1.setAlignment(ParagraphAlignment.CENTER);
XWPFRun r1 = p1.createRun();
r1.setText("Hello, POI!");
r1.setBold(true);
r1.setFontSize(24);
XWPFParagraph p2 = doc.createParagraph();
p2.setSpacingAfter(200);
XWPFRun r2 = p2.createRun();
r2.setText("This is a paragraph with formatting.");
r2.setFontFamily("微软雅黑");
r2.setColor("FF0000");
FileOutputStream out = new FileOutputStream("example.docx");
doc.write(out);
out.close();
doc.close();
}
}高级操作
添加表格
XWPFTable table = doc.createTable(2, 3); //2行3列
table.getRow(0).getCell(0).setText("Name");
table.getRow(0).getCell(1).setText("Age");
table.getRow(0).getCell(2).setText("City");插入图片
FileInputStream is = new FileInputStream("logo.png");
String blipId = paragraph.getDocument().addPictureData(is, XWPFDocument.PICTURE_TYPE_PNG);
run.addPicture(blipId, XWPFDocument.PICTURE_TYPE_PNG, "logo.png", Units.toEMU(200), Units.toEMU(100));生成目录
POI不支持直接生成Word目录(TOC),需要借助OpenXML或手动注字段代码,较为复杂,具体可参考官方文档。
注意事项
- POI对.doc格式(旧版)支持有限,建议使用.docx格式。
- 大文档生成时注意内存溢出,可使用
SXWPFDocument(流式处理,需结合XWPFDocument)。 - 模板填充可使用
XWPFDocument配合变量替换。
结语
Apache POI提供了丰富的API,灵活运用可生成任意复杂度的Word文档。建议深入阅读官方文档。上述示例已覆盖核心功能,快动手尝试吧!