这个简短的分步指南介绍了如何使用 Java 在 Word 文档中创建表。在本教程的帮助下,您可以插入一个或多个表来根据您的要求组织信息。在最后一步,输出文件保存为 DOCX 文件,但您可以将其保存为任何 Word 文件格式。
使用 Java 在 Word 文档中创建表格的步骤
- 从 Maven 存储库添加 Aspose.Words for Java
- 使用 Document 类初始化一个空的 Word 文档
- 初始化一个新的 Table 类实例
- 在表中创建一个新的 Row
- 创建一个单元格并在单元格内添加一个新段落
- 在文档末尾插入表格
- 将带表格的 Word 文档另存为 DOCX 文件
使用这些步骤,我们可以使用 Java 在 Word 文档中插入表格。我们可以将信息添加到单元格中,并使用 Java 以编程方式组织文档内容。
使用 Java 在 Word 文档中创建表格的代码
import com.aspose.words.Cell; | |
import com.aspose.words.Document; | |
import com.aspose.words.License; | |
import com.aspose.words.Paragraph; | |
import com.aspose.words.Row; | |
import com.aspose.words.Run; | |
import com.aspose.words.Table; | |
public class CreateTableInWordUsingJava | |
{ | |
public static void main(String[] args) throws Exception { //main function for CreateTableInWordUsingJava class | |
// Initialize a license to avoid trial version watermark in the output Word file after adding comments | |
License license = new License(); | |
license.setLicense("Aspose.Words.lic"); | |
// Initialize a blank Word document using Document class | |
Document wordDocument = new Document(); | |
// Initialize a new Table class instance | |
Table wordTable = new Table(wordDocument); | |
// Create a new Row in the Table | |
wordTable.getRows().add(new Row(wordDocument)); | |
// Create single Cell in the Table Row | |
wordTable.getFirstRow().getCells().add(new Cell(wordDocument)); | |
// Add a new Paragraph inside Cell | |
wordTable.getFirstRow().getFirstCell().appendChild(new Paragraph(wordDocument)); | |
// Add text content inside the Table Cell | |
wordTable.getFirstRow().getFirstCell().getFirstParagraph().getRuns().add(new Run(wordDocument, "Text in Table Row 1 and Cell 1")); | |
// Insert a Table at the last portion of Word Document | |
wordDocument.getFirstSection().getBody().insertBefore(wordTable, wordDocument.getFirstSection().getBody().getLastParagraph()); | |
// Save Word document with Table in DOCX format | |
wordDocument.save("word_table.docx"); | |
} | |
} |
在这段 Java 代码中,我们初始化了一个空白 Word 文档,然后添加了一个表格并将内容插入到特定的单元格中。然后在最后插入表格来演示如何在 Word 文档中使用 Java 制作表格。
在本教程中,我们学习了如何使用 Java 在 Word 文档中插入表格。但是,如果您想在 Word 文档中的表格中添加一行,则可以参考文章 如何使用 Java 在 DOCX 中的表中添加行。