テーブルを作成する

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

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

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

テーブルのプロパティ Aspose.Wordsのデフォルト
Border Style Single
Border Width 1/2 pt
Border Color 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-.NET.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(ArtifactsDir + "WorkingWithTables.CreateSimpleTable.docx");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.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.LeftIndent = 20.0;
// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;
builder.CellFormat.Width = 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.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
// Reset height and define a different height rule for table body.
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();
builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.FormattedTable.docx");

次のコード例は、DocumentBuilder を使用してネストされたテーブルを挿入する方法を示しています。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.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.FirstParagraph);
// Build the inner table.
builder.InsertCell();
builder.Writeln("Inner Table Cell 1");
builder.InsertCell();
builder.Writeln("Inner Table Cell 2");
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.NestedTable.docx");
view raw nested-table.cs hosted with ❤ by GitHub

DOM (Document Object Model) 経由でテーブルを作成する

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

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.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.FirstSection.Body.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.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.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.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));
// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
doc.Save(ArtifactsDir + "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-.NET.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(ArtifactsDir + "WorkingWithTables.InsertTableFromHtml.docx");

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

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

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "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.Clone(true);
table.ParentNode.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.ParentNode.InsertAfter(new Paragraph(doc), table);
doc.Save(ArtifactsDir + "WorkingWithTables.CloneCompleteTable.docx");

次のコード例は、テーブルの最後の行のクローンを作成し、それをテーブルに追加する方法を示しています。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
Row clonedRow = (Row) table.LastRow.Clone(true);
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into.
foreach (Cell cell in clonedRow.Cells)
cell.RemoveAllChildren();
table.AppendChild(clonedRow);
doc.Save(ArtifactsDir + "WorkingWithTables.CloneLastRow.docx");

データ ソースのレコードごとに動的に増加するテーブルをドキュメント内に作成する場合、上記の方法はお勧めできません。代わりに、リージョンで Mail merge を使用すると、目的の出力をより簡単に実現できます。このテクニックについて詳しくは、Mail Merge とリージョン セクションをご覧ください。

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

Aspose.Words には、ドキュメント内に新しいテーブルを作成するためのいくつかの方法が用意されています。各方法には独自の長所と短所があるため、どちらを使用するかは特定の状況によって決まります。

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

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