java如何生成word文档
使用Apache POI库生成Word文档
Apache POI是Apache软件基金会的开源库,提供对Microsoft Office格式文件的读写支持。XWPF组件专门用于操作Word文档(.docx格式)。
添加Maven依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
基础示例代码:
import org.apache.poi.xwpf.usermodel.*;
public class WordGenerator {
public static void createSimpleDocument() throws Exception {
XWPFDocument document = new XWPFDocument();
// 添加标题
XWPFParagraph title = document.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER);
XWPFRun titleRun = title.createRun();
titleRun.setText("文档标题");
titleRun.setBold(true);
titleRun.setFontSize(16);
// 添加正文
XWPFParagraph para = document.createParagraph();
XWPFRun run = para.createRun();
run.setText("这是一段示例文本。");
// 保存文件
FileOutputStream out = new FileOutputStream("output.docx");
document.write(out);
out.close();
document.close();
}
}
使用docx4j库生成Word文档
docx4j是另一个专门处理Office Open XML格式的Java库,更适合复杂文档操作。
Maven依赖:
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
<version>11.4.5</version>
</dependency>
示例代码:
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
public class Docx4jExample {
public static void main(String[] args) throws Exception {
WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
MainDocumentPart documentPart = wordPackage.getMainDocumentPart();
documentPart.addStyledParagraphOfText("Title", "文档标题");
documentPart.addParagraphOfText("正文内容");
wordPackage.save(new File("output.docx"));
}
}
使用模板引擎生成Word文档
对于需要动态内容的场景,可以考虑使用模板引擎:
FreeMarker模板示例(需要将Word文档另存为XML格式作为模板):
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setDirectoryForTemplateLoading(new File("templates"));
Template template = cfg.getTemplate("word_template.ftl");
Map<String, Object> data = new HashMap<>();
data.put("title", "动态标题");
data.put("content", "动态内容");
Writer out = new FileWriter("output.xml");
template.process(data, out);
out.close();
高级功能实现
表格创建示例(使用Apache POI):
XWPFTable table = document.createTable(3, 4);
table.getRow(0).getCell(0).setText("Header1");
table.getRow(0).getCell(1).setText("Header2");
for(int row=1; row<3; row++) {
for(int col=0; col<4; col++) {
table.getRow(row).getCell(col).setText("Data " + row + col);
}
}
图片插入示例:

XWPFRun run = paragraph.createRun();
FileInputStream is = new FileInputStream("image.jpg");
run.addPicture(is, Document.PICTURE_TYPE_JPEG, "image.jpg", Units.toEMU(200), Units.toEMU(150));
is.close();
注意事项
所有示例都需要处理IOException,实际使用时应添加异常处理逻辑。对于大型文档生成,注意及时关闭资源防止内存泄漏。较新版本的Word文档应使用.docx格式(OOXML),而非旧的.doc格式(二进制格式)。






