この簡単なステップバイステップガイドでは、Javaを使用してWord文書でテーブルを作成する方法について説明します。このチュートリアルを使用すると、1つ以上のテーブルを挿入して、要件に応じて情報を整理できます。最後のステップで、出力ファイルは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文書を初期化してから、テーブルを追加し、特定のセルにコンテンツを挿入しました。次に、テーブルを最後に挿入して、Javaを使用してWord文書でテーブルを作成する方法を示します。
このチュートリアルでは、Javaを使用してWord文書にテーブルを挿入する方法を学びました。ただし、Word文書のテーブルに行を追加する場合は、記事Javaを使用してDOCXのテーブルに行を追加する方法を参照してください。