テーブルを作成する

Aspose.Wordsを使用すると、ユーザーは文書内にテーブルを最初から作成でき、そのためのいくつかの異なる方法が提供されます。 この記事では、各メソッドを使用して書式設定されたテーブルをドキュメントに追加する方法の詳細と、記事の最後にある各メソッドの比較について

デフォルトのテーブルスタイル

新しく作成されたテーブルには、Microsoft Wordで使用されているものと同様のデフォルト値が与えられます:

テーブルプロパティ Aspose.Wordsのデフォルト
Border Style Single
Border Width 1/2 pt
境界線の色 Black
Left and Right Padding 5.4 pts
AutoFit Mode AutoFit to Window
Allow AutoFit True

DocumentBuilderでテーブルを作成する

Aspose.Wordsでは、ユーザーはDocumentBuilderを使用して文書内にテーブルを作成できます。 テーブルを作成するための基本的なアルゴリズムは次のとおりです:

  1. テーブルをStartTableで開始します
  2. InsertCellを使用してテーブルにセルを追加する–これにより、新しい行が自動的に開始されます
  3. 必要に応じて、CellFormatプロパティを使用してセルの書式を指定します
  4. WritelnInsertImageなどの適切なDocumentBuilderメソッドを使用してセルの内容を挿入します
  5. 行が完了するまで、手順2~4を繰り返します
  6. 現在の行を終了するにはEndRowを呼び出します
  7. 必要に応じて、RowFormatプロパティを使用して行の書式を指定します
  8. テーブルが完了するまで、手順2~7を繰り返します
  9. テーブルの構築を完了するにはEndTableを呼び出します

テーブルを作成するプロセスは、次の図ではっきりと見ることができます:

creating-table-process

次のコード例は、既定の書式設定でDocumentBuilderを使用して単純なテーブルを作成する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Start building the table.
builder.startTable();
builder.insertCell();
builder.write("Row 1, Cell 1 Content.");
// Build the second cell.
builder.insertCell();
builder.write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.endRow();
// Build the first cell of the second row.
builder.insertCell();
builder.write("Row 2, Cell 1 Content");
// Build the second cell.
builder.insertCell();
builder.write("Row 2, Cell 2 Content.");
builder.endRow();
// Signal that we have finished building the table.
builder.endTable();
doc.save(getArtifactsDir() + "WorkingWithTables.CreateSimpleTable.docx");

次のコード例は、DocumentBuilderを使用して書式設定されたテーブルを作成する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
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();
builder.endTable();
doc.save(getArtifactsDir() + "WorkingWithTables.FormattedTable.docx");

次のコード例は、DocumentBuilderを使用して入れ子になったテーブルを挿入する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
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();
doc.save(getArtifactsDir() + "WorkingWithTables.NestedTable.docx");

DOMを使用してテーブルを作成する(ドキュメントオブジェクトモデル)

特定の位置に新しいTableノードを追加することで、テーブルをDOMに直接挿入できます。

テーブルノードの作成直後に、テーブル自体は完全に空になります。つまり、まだ行とセルが含まれていないことに注意してください。 テーブルに行とセルを挿入するには、適切なRowCellの子ノードをDOMに追加します。

次のコード例は、適切な子ノードをドキュメントツリーに追加して、新しいテーブルを最初から作成する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
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"));
doc.save(getArtifactsDir() + "WorkingWithTables.InsertTableDirectly.docx");

HTMLからテーブルを作成する

Aspose.Wordsは、InsertHtmlメソッドを使用して、HTMLソースからドキュメントにコンテンツを挿入することをサポートします。 入力は、完全なHTMLページまたは部分的なスニペットにすることができます。

このInsertHtmlメソッドを使用すると、ユーザーは次のようなテーブルタグを介して文書にテーブルを挿入できます<table>, <tr>, <td>.

次のコード例は、HTMLタグを含む文字列からドキュメントにテーブルを挿入する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
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>");
doc.save(getArtifactsDir() + "WorkingWithTables.InsertTableFromHtml.docx");

既存のテーブルのコピーを挿入する

ドキュメント内の既存のテーブルに基づいてテーブルを作成する必要がある場合がよくあります。 すべての書式設定を保持しながらテーブルを複製する最も簡単な方法は、deepCloneメソッドを使用してテーブルノードを複製することです。

同じ手法を使用して、既存の行またはセルのコピーをテーブルに追加できます。

次のコード例は、ノードコンストラクターを使用してテーブルを複製する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "Tables.docx");
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
// Clone the table and insert it into the document after the original.
Table tableClone = (Table) table.deepClone(true);
table.getParentNode().insertAfter(tableClone, table);
// Insert an empty paragraph between the two tables,
// or else they will be combined into one upon saving this has to do with document validation.
table.getParentNode().insertAfter(new Paragraph(doc), table);
doc.save(getArtifactsDir() + "WorkingWithTables.CloneCompleteTable.docx");

次のコード例は、テーブルの最後の行を複製してテーブルに追加する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "Tables.docx");
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
Row clonedRow = (Row) table.getLastRow().deepClone(true);
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into.
for (Cell cell : (Iterable<Cell>) clonedRow.getCells())
cell.removeAllChildren();
table.appendChild(clonedRow);
doc.save(getArtifactsDir() + "WorkingWithTables.CloneLastRow.docx");

データソースからの各レコードで動的に成長するドキュメント内のテーブルを作成する場合は、上記の方法はお勧めしません。 代わりに、領域でMail mergeを使用すると、目的の出力がより簡単に達成されます。 この技術についての詳細を学ぶことができます 地域を持つMail Merge セクション。

テーブルを作成する方法を比較する

Aspose.Wordsは、文書内に新しいテーブルを作成するためのいくつかのメソッドを提供します。 各方法には独自の長所と短所があるため、使用する選択は特定の状況に依存することがよくあります。

テーブルを作成するこれらの方法を詳しく見て、その長所と短所を比較してみましょう:

メソッド 利点 デメリット
経由DocumentBuilder テーブルやその他のドキュメントコンテンツを挿入するための標準的な方法 同じビルダーインスタンスで同時に多くの種類のテーブルを作成するのが難しい場合があります
経由DOM DocumentBuilderを使用せずにノードを直接DOMに作成して挿入する周囲のコードに適しています ほとんどの操作を実行する前に、EnsureMinimumを呼び出して不足している子ノードを作成する必要があります
からHTML 次のようなタグを使用してHTMLソースから新しいテーブルを作成できます<table>, <tr>, <td> すべての可能なMicrosoft Wordテーブル形式をHTMLに適用できるわけではありません
既存のテーブルのクローン作成 すべての行とセルの書式設定を保持しながら、既存のテーブルのコピーを作成できます テーブルを使用する準備が整う前に、適切な子ノードを削除する必要があります