创建一个包含标题、段落和表格的简单文档。
确保你的项目中已经添加了 Apache POI 的依赖。如果你使用的是 Maven,可以在 pom.xml
中添加以下内容:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version> <!-- 确保版本号是最新的 -->
</dependency>
如果是 Gradle:
implementation 'org.apache.poi:poi-ooxml:5.2.3'
以下是使用 Apache POI 创建 Word 文档的完整代码示例:
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
public class WordDocumentGenerator {
public static void main(String[] args) {
// 创建一个新的 Word 文档
XWPFDocument document = new XWPFDocument();
try {
// 添加标题
addTitle(document, "这是一个Word文档示例", 1);
// 添加段落
addParagraph(document, "这是第一段文字。Apache POI 是一个强大的库,用于处理 Microsoft Office 文档。");
// 添加表格
addTable(document);
// 保存文档到文件
saveDocument(document, "example.docx");
System.out.println("Word 文档已生成!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 添加标题到文档
*/
private static void addTitle(XWPFDocument document, String titleText, int level) {
XWPFParagraph title = document.createParagraph();
title.setAlignment(ParagraphAlignment.CENTER); // 居中对齐
title.setStyle("Heading" + level); // 设置标题样式
XWPFRun titleRun = title.createRun();
titleRun.setText(titleText);
titleRun.setBold(true);
titleRun.setFontSize(18);
}
/**
* 添加段落到文档
*/
private static void addParagraph(XWPFDocument document, String paragraphText) {
XWPFParagraph paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT); // 左对齐
XWPFRun run = paragraph.createRun();
run.setText(paragraphText);
run.setFontSize(12);
}
/**
* 添加表格到文档
*/
private static void addTable(XWPFDocument document) {
// 创建一个 3 行 4 列的表格
XWPFTable table = document.createTable(3, 4);
table.setWidth("100%"); // 设置表格宽度为 100%
// 填充表头
XWPFTableRow headerRow = table.getRow(0);
headerRow.getCell(0).setText("列1");
headerRow.getCell(1).setText("列2");
headerRow.getCell(2).setText("列3");
headerRow.getCell(3).setText("列4");
// 填充数据行
XWPFTableRow dataRow1 = table.getRow(1);
dataRow1.getCell(0).setText("A1");
dataRow1.getCell(1).setText("B1");
dataRow1.getCell(2).setText("C1");
dataRow1.getCell(3).setText("D1");
XWPFTableRow dataRow2 = table.getRow(2);
dataRow2.getCell(0).setText("A2");
dataRow2.getCell(1).setText("B2");
dataRow2.getCell(2).setText("C2");
dataRow2.getCell(3).setText("D2");
}
/**
* 保存文档到文件
*/
private static void saveDocument(XWPFDocument document, String filePath) throws IOException {
try (FileOutputStream out = new FileOutputStream(filePath)) {
document.write(out); // 写入文件
}
document.close(); // 关闭文档
}
}
XWPFDocument
类创建一个新的 Word 文档。XWPFParagraph
和 XWPFRun
创建段落,并设置文本、字体大小和加粗等样式。XWPFParagraph
和 XWPFRun
,可以灵活设置对齐方式、字体大小等属性。XWPFTable
创建表格,并通过 getRow
和 getCell
方法填充数据。FileOutputStream
将文档写入到指定路径。运行上述代码后,会在项目的根目录下生成一个名为 example.docx
的 Word 文档,其内容如下:
xmlbeans
或 commons-compress
),请确保它们的版本与 Apache POI 兼容。SXSSFWorkbook
)。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。