如何使用 Java 在 Word 中的表格中添加一行

这个简短的教程解释了如何在 Word 中使用 Java 向表中添加一行。在本教程的帮助下,您还可以使用 Java 在 Word 表中插入多行。最后,此输出文件保存为 DOCX 但是,您可以将其保存为任何 Word 文件格式。

使用 Java 向 Word 中的表格添加行的步骤

  1. 配置您的项目以从 Maven 存储库添加 Aspose.Words for Java
  2. 使用 Document 对象打开一个包含 Table 的 word 文件
  3. 获取对 Word 文件中表的引用
  4. 创建一个新的 Row 并在列中添加所需的数据
  5. 在表格的第一行之后插入这一行
  6. 克隆现有行并清除其内容
  7. 用一些数据填充多行
  8. 将行添加到 Word 中的现有表格末尾
  9. 将行添加到现有表后保存文件

使用这些步骤,我们打开包含表格的 Word 文件并在其中插入一行。类似地,我们可以通过将示例数据填充到多行并将这些行添加到表的末尾来使用 Java向 Word 中的表添加多行。

使用 Java 在 Word 中向表中添加新行的代码

import com.aspose.words.License;
import com.aspose.words.Paragraph;
import com.aspose.words.Row;
import com.aspose.words.Run;
import com.aspose.words.Cell;
import com.aspose.words.Document;
import com.aspose.words.Table;
public class HowToAddARowToATableInWordUsingJava {
public static void main() throws Exception { //main() function for HowToAddARowToATableInWordUsingJava
// Instantiate a license to remove trial version watermark in the output Word file
License license = new License();
license.setLicense("Aspose.Words.lic");
// Open Word Document having a table in it
Document WordDocumentWithTable = new Document("MS Word.docx");
// Get the reference to the table by index
Table tableToAddRowsTo = WordDocumentWithTable.getFirstSection().getBody().getTables().get(0);
// Instantiate a new Row class object
Row row = new Row(WordDocumentWithTable);
// Add Cells to the collection of cells of the newly created row
for (int i = 0; i < tableToAddRowsTo.getRows().get(0).getCells().getCount(); i++)
{
Cell cell = new Cell(WordDocumentWithTable);
cell.appendChild(new Paragraph(WordDocumentWithTable));
cell.getFirstParagraph().getRuns().add(new Run(WordDocumentWithTable, "Text in Cell " + i));
row.getCells().add(cell);
}
// Insert the new Row after the first Row in the table
tableToAddRowsTo.getRows().insert(1, row);
// Deep Clone an existing Row from the Table
Row cloneOfRow = (Row)tableToAddRowsTo.getFirstRow().deepClone(true);
// Remove all content from all Cells in the cloned row
for (Cell cell : cloneOfRow)
{
cell.removeAllChildren();
cell.ensureMinimum();
}
// Add number of rows say 10 to the end of table
for (int iRowCount = 0; iRowCount < 10; iRowCount++)//You can set any number of rows instead of 10
{
Row emptyRow = (Row)cloneOfRow.deepClone(true);
tableToAddRowsTo.getRows().add(emptyRow);
}
WordDocumentWithTable.save("Added Rows to Table to MS Word.docx");
}
}

在这个 Java 代码中,我们使用 Document、Table 和 Row 类来访问 Word 文档中的不同元素,并使用 Java 向 Word 中的现有表格添加一行。在代码的最后,提供了使用 Java 在 Word 表中添加多行的示例,以便将一行多次添加到循环中的行集合中,以进行演示。

在本教程中,我们打开了一个现有文件,但是如果您想创建一个新的 Word 文档,请参阅文章 如何使用 Java 创建 Word 文档。请注意,我们不需要 MS Words 或 Interop 在系统上可用以运行上述代码。

 简体中文