借助文档控件Aspose.Words,使用 Java 在 Word 文档中创建表格

Microsoft Word 是一种流行的文字处理应用程序,用于创建各种类型的文档。这些文档可能包含多种类型的元素,包括文本、图像、表格和图表。当涉及到用 Java 自动创建和操作文档时,您可能需要一个轻松的解决方案来在 Word 文档中创建表格。因此,在这篇博文中,我们将探讨如何在 Java 应用程序中在 Word 文档中创建表格。

Aspose.Words是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。

Aspose API支持流行文件格式处理,并允许将各类文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。

Aspose.words for.net下载 Aspose.words for for java下载

在 Word 文档中创建表格的 Java 库

Aspose.Words for Java是一个 API,允许 Java 开发人员以编程方式处理 Microsoft Word 文档。它提供了用于创建、修改和操作 Word 文档的广泛功能,使其成为自动化文档生成和处理任务的宝贵工具。我们将使用该库将表格插入到 Word 文档中。

您可以下载该库或使用以下 Maven 配置来安装它。

复制代码
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java API</name>
<url>https://repository.aspose.com/repo/</url>
</repository>

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>23.10</version>
<classifier>jdk17</classifier>
</dependency>
使用 Java 在 Word 文档中创建表格

使用 Aspose.Words for Java 在 Word 文档中创建表格有两种方法:

  • 使用文档生成器
  • 使用 DOM(文档对象模型)

您可以选择最适合您要求的方法。那么让我们详细探讨一下这些方法。

使用 DocumentBuilder 创建表

DocumentBuilder类为您提供了一种快速、简单的方法来从头开始创建动态文档或处理现有文档。它提供了一系列用于插入各种内容元素的功能,例如文本、复选框、OLE 对象、段落、列表、表格、图像等。

以下是在Java中使用DocumentBuilder类在Word文档中创建表格的步骤。

  • 创建Document类的对象来加载或创建Word文档。
  • 创建DocumentBuilder类的对象。
  • 使用DocumentBuilder.startTable()方法 启动一个表
  • 使用DocumentBuilder.insertCell()方法 插入单元格
  • (可选)对单元格应用格式设置,例如字体和对齐方式。
  • 使用DocumentBuilder.write()方法 将文本插入单元格。
  • 根据需要重复将单元格和文本插入到单元格中。
  • 使用DocumentBuilder.endRow() 方法完成插入单元格时结束一行
  • 使用DocumentBuilder.endTable() 方法插入所有行时结束表
  • *使用Document.save()*方法保存 Word 文档。

以下代码片段展示了如何使用 Java 在 Word 文档中创建表格。

复制代码
// Create or load document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a new table and insert cell.
Table table = builder.startTable();
builder.insertCell();

// Table wide formatting must be applied after at least one row is present in the table.
table.setLeftIndent(20.0);

// Set height and define the height rule for the header row.
builder.getRowFormat().setHeight(40.0);
builder.getRowFormat().setHeightRule(HeightRule.AT_LEAST);

builder.getCellFormat().getShading().setBackgroundPatternColor(new Color((198), (217), (241)));
builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
builder.getFont().setSize(16.0);
builder.getFont().setName("Arial");
builder.getFont().setBold(true);

builder.getCellFormat().setWidth(100.0);
builder.write("Header Row,\n Cell 1");

// We don't need to specify this cell's width because it's inherited from the previous cell.
builder.insertCell();
builder.write("Header Row,\n Cell 2");

builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Header Row,\n Cell 3");
builder.endRow();

builder.getCellFormat().getShading().setBackgroundPatternColor(Color.WHITE);
builder.getCellFormat().setWidth(100.0);
builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);

// Reset height and define a different height rule for table body.
builder.getRowFormat().setHeight(30.0);
builder.getRowFormat().setHeightRule(HeightRule.AUTO);
builder.insertCell();

// Reset font formatting.
builder.getFont().setSize(12.0);
builder.getFont().setBold(false);

builder.write("Row 1, Cell 1 Content");
builder.insertCell();
builder.write("Row 1, Cell 2 Content");

builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Row 1, Cell 3 Content");
builder.endRow();

builder.insertCell();
builder.getCellFormat().setWidth(100.0);
builder.write("Row 2, Cell 1 Content");

builder.insertCell();
builder.write("Row 2, Cell 2 Content");

builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Row 2, Cell 3 Content.");
builder.endRow();

// End table.
builder.endTable();

// Save document.
doc.save("table.docx");

以下是我们使用上面的代码示例创建的表的屏幕截图。

使用 DOM 创建表

文档对象模型 (DOM)是 Word 文档的内存中表示形式,允许您以编程方式读取、操作和修改 Word 文档的内容和格式。以下步骤演示如何使用 DOM 在 Word 文档中创建表格。

  • 创建Document类的对象来加载或创建Word文档。
  • 创建Table 类的对象,并使用*Document.getFirstSection().getBody().appendChild(Table)*方法将表格插入到文档中。
  • 创建Row 类的对象并使用*Table.appendChild(Row)*方法将其插入表中。
  • 创建Cell类的对象,设置格式选项并向单元格添加文本。
  • *使用Row.appendChild(Cell)*方法将单元格插入行中。
  • 对所需数量的行重复此过程。
  • *使用Document.save()*方法保存 Word 文档。

以下代码片段展示了如何使用 Java 在 Word 文档中创建表格。

复制代码
// Create or load document.
Document doc = new Document();

// We start by creating the table object. Note that we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
doc.getFirstSection().getBody().appendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid. In this case, a valid table should have at least one Row and one cell.

// Instead, we will handle creating the row and table ourselves.
// This would be the best way to do this if we were creating a table inside an algorithm.
Row row = new Row(doc);
row.getRowFormat().setAllowBreakAcrossPages(true);
table.appendChild(row);

// We can now apply any auto fit settings.
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);

Cell cell = new Cell(doc);
cell.getCellFormat().getShading().setBackgroundPatternColor(Color.BLUE);
cell.getCellFormat().setWidth(80.0);
cell.appendChild(new Paragraph(doc));
cell.getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 1 Text"));

row.appendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.appendChild(cell.deepClone(false));
row.getLastCell().appendChild(new Paragraph(doc));
row.getLastCell().getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Save document.
doc.save("table.docx");
在 Word 文档中插入嵌套表格

还可能存在这样的情况:您需要创建位于父表单元格内的嵌套表。您无需经过复杂的过程即可做到这一点。首先,创建一个父表,然后调用*DocumentBuilder.moveTo(Cell.getFirstParagraph())*方法将控件移动到父表的所需单元格内。完成后,以同样的方式创建一个新表。

以下代码片段展示了如何使用 Java 在 Word 文档中创建嵌套表格。

复制代码
// Create or load document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert cell.
Cell cell = builder.insertCell();
builder.writeln("Outer Table Cell 1");

builder.insertCell();
builder.writeln("Outer Table Cell 2");

// This call is important to create a nested table within the first table.
// Without this call, the cells inserted below will be appended to the outer table.
builder.endTable();

// Move to the first cell of the outer table.
builder.moveTo(cell.getFirstParagraph());

// Build the inner table.
builder.insertCell();
builder.writeln("Inner Table Cell 1");
builder.insertCell();
builder.writeln("Inner Table Cell 2");
builder.endTable();

// Save document.
doc.save("table.docx");

以下是我们上面创建的嵌套表的屏幕截图。

在 Java 中从 HTML 创建 Word 表

您还可以使用 HTML 字符串在 Word 文档中创建表格,以下是要遵循的步骤。

  • 创建Document类的对象来加载或创建Word文档。
  • 创建DocumentBuilder类的对象。
  • *使用DocumentBuilder.insertHtml(String)*方法将表的 HTML 字符串插入到文档中。
  • *最后,使用Document.save()*方法保存文档。

下面是从 HTML 字符串生成 Word 表格的代码片段。

复制代码
// Create or load document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Note that AutoFitSettings does not apply to tables inserted from HTML.
builder.insertHtml("<table>"
"<tr>"
"<td>Row 1, Cell 1</td>"
"<td>Row 1, Cell 2</td>"
"</tr>"
"<tr>"
"<td>Row 2, Cell 2</td>"
"<td>Row 2, Cell 2</td>"
"</tr>"
"</table>");

// Save document.
doc.save("table.docx");
结论

在这篇博文中,我们探讨了如何使用 Java 在 Word 文档中创建表格。您已经了解了如何使用文档生成器或 DOM 创建表、创建嵌套表以及从 HTML 字符串创建表。通过安装该库并遵循指南,您可以轻松地将表创建功能集成到您的 Java 应用程序中。

相关推荐
AI多Agent协作实战派10 小时前
AI多Agent协作系统实战(十七):凌晨4点,我的AI系统在“假装工作“——3个bug同时爆炸的5小时
java·前端·bug
gaolei_eit10 小时前
Java+Ai+vue
java·spring·maven
qq_25183645710 小时前
基于java Web 动漫视频网站毕业论文
java·开发语言·前端
LayZhangStrive10 小时前
JUC相关的函数、注解、变量杂记
java·面试·多线程·juc
未秃头的程序猿10 小时前
给公司做了个AI客服Agent,用的Spring AI 1.0,3天上线领导拍板了
java·后端·ai编程
曹牧10 小时前
Eclipse 批量文本替换
java·ide·eclipse
程序员清风10 小时前
OpenAI官方发布最新提示词技巧!
java·后端·面试
一只枫林10 小时前
MySQL内、外连接知识点汇总
java·前端·数据库
梅头脑10 小时前
写了3年CRUD,volatile和synchronized的区别还是答不清——直到我画出了这张三性两锁边界图
java
暮暮祈安10 小时前
Celery 新手入门指南
java·数据库·python·flask·httpx