次の方法で共有


ワープロ ドキュメントに表を挿入する

このトピックでは、Open XML SDK for Office のクラスを使用して、プログラムによってワープロ ドキュメントにテーブルを挿入する方法について説明します。

WordprocessingDocument オブジェクトの取得

既存のドキュメントを開くには、次の using ステートメントに示すように、WordprocessingDocument クラスをインスタンス化します。 同じステートメントで、 Open メソッドを使用して、指定した filepath でワープロ ファイルを開き、Boolean パラメーターを true に設定してドキュメントの編集を有効にします。

using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true))

v3.0.0 以降では、using ステートメントに依存することを優先して、Close() メソッドが削除されました。 これにより、閉じかっこに達したときに、 Dispose() メソッドが自動的に呼び出されます。 using ステートメントに続くブロックは、using ステートメントで作成または名前付けされたオブジェクトのスコープを確立します。 Open XML SDK の WordprocessingDocument クラスは、IDisposable実装の一部としてオブジェクトを自動的に保存および閉じます。また、ブロックを終了するとDispose()が自動的に呼び出されるため、using ステートメントを使用する限り、明示的にSave()またはDispose()を呼び出す必要はありません。

表の構造

WordProcessingMLドキュメントの基本的なドキュメント構造は、document要素とbody要素で構成され、その後に段落を表す p などの 1 つ以上のブロック レベル要素が続きます。 段落には、1 つ以上の r 要素が含まれています。 r はセクションを表し、書式などの共通のプロパティ セットを含むテキストの領域です。 実行には、1 つ以上の t 要素が含まれています。 t要素には、テキストの範囲が含まれています。ドキュメントには、この例のようにテーブルが含まれている場合があります。 表は、行と列に配置された一連の段落 (および他のブロック レベル コンテンツ) です。 WordprocessingMLのテーブルは、HTML テーブル タグに似た tbl 要素を使用して定義されます。 空の 1 セル テーブル (つまり、1 行 1 列のテーブル) と、すべての辺に 1 つのポイント罫線を使用するとします。 この表は、次の WordprocessingML マークアップ セグメントで表されます。

    <w:tbl>
      <w:tblPr>
        <w:tblW w:w="5000" w:type="pct"/>
        <w:tblBorders>
          <w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/>
          <w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/>
          <w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/>
          <w:right w:val="single" w:sz="4" w:space="0" w:color="auto"/>
        </w:tblBorders>
      </w:tblPr>
      <w:tblGrid>
        <w:gridCol w:w="10296"/>
      </w:tblGrid>
      <w:tr>
        <w:tc>
          <w:tcPr>
            <w:tcW w:w="0" w:type="auto"/>
          </w:tcPr>
          <w:p/>
        </w:tc>
      </w:tr>
    </w:tbl>

このテーブルは、 tblW 要素を使用してページ幅の 100% のテーブル全体のプロパティ、 tblBorders 要素を使用するテーブル罫線のセット、 tblGrid 要素を使用してテーブル内の共有垂直エッジのセットを定義するテーブル グリッド、および tr 要素を使用した単一のテーブル行を指定します。

サンプル コードの動作のしくみ

サンプル コードでは、 using ステートメントでドキュメントを開いた後、新しい Table オブジェクトを作成します。 次に、 TableProperties オブジェクトを作成し、その境界線情報を指定します。 TableProperties クラスには、OpenXmlElement 型のparams配列を受け取るオーバーロードされたコンストラクター TableProperties()が含まれています。 コードでは、このコンストラクターを使用して、境界ごとにBorderType オブジェクトを持つTableProperties オブジェクトをインスタンス化し、各BorderTypeをインスタンス化し、オブジェクト初期化子を使用してその値を指定します。 インスタンス化されたら、 TableProperties オブジェクトをテーブルに追加します。

// Create an empty table.
Table table = new Table();

// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
    new TableBorders(
        new TopBorder()
        {
            Val =
            new EnumValue<BorderValues>(BorderValues.Dashed),
            Size = 24
        },
        new BottomBorder()
        {
            Val =
            new EnumValue<BorderValues>(BorderValues.Dashed),
            Size = 24
        },
        new LeftBorder()
        {
            Val =
            new EnumValue<BorderValues>(BorderValues.Dashed),
            Size = 24
        },
        new RightBorder()
        {
            Val =
            new EnumValue<BorderValues>(BorderValues.Dashed),
            Size = 24
        },
        new InsideHorizontalBorder()
        {
            Val =
            new EnumValue<BorderValues>(BorderValues.Dashed),
            Size = 24
        },
        new InsideVerticalBorder()
        {
            Val =
            new EnumValue<BorderValues>(BorderValues.Dashed),
            Size = 24
        }
    )
);

// Append the TableProperties object to the empty table.
table.AppendChild<TableProperties>(tblProp);

コードでは、表の行を作成します。 コードのこのセクションでは、オーバーロードされた Append メソッドを広範に使用します。このメソッドは、継承 OpenXmlElement から派生したクラスです。 Append メソッドは、単一の要素を追加するか、XML ツリーの一部を、特定の親要素の下にある子要素のリストの末尾に追加する方法を提供します。 次に、個々のテーブル セルを表す TableCell オブジェクトを作成し、TableCellProperties オブジェクトを使用してテーブル セルの width プロパティと、Text オブジェクトを使用してセルの内容 ("Hello、World!") を指定します。 Open XML Wordprocessing スキーマでは、段落要素 (<p\>) に実行要素 (<r\>) が含まれており、テキスト要素 (<t\>) が含まれます。 API を使用してテーブル セル内にテキストを挿入するには、セルに挿入するテキストを含むText オブジェクトを含むRun オブジェクトを含むParagraph オブジェクトを作成する必要があります。 次に、 Paragraph オブジェクトを TableCell オブジェクトに追加します。 これで、テキストをセルに挿入するための適切な XML 構造が作成されます。 その後、TableRow オブジェクトにTableCellが追加されます。

// Create a row.
TableRow tr = new TableRow();

// Create a cell.
TableCell tc1 = new TableCell();

// Specify the width property of the table cell.
tc1.Append(new TableCellProperties(
    new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

// Specify the table cell content.
tc1.Append(new Paragraph(new Run(new Text("some text"))));

// Append the table cell to the table row.
tr.Append(tc1);

続けて、2 個目の表のセルを作成します。 コードの最後のセクションでは、既存のTableCell オブジェクトのOuterXml プロパティを唯一の引数として受け取るオーバーロードされたTableCell コンストラクター TableCell(String)を使用して、別のテーブル セルを作成します。 2 番目のテーブル セルを作成した後、コードはTableRowTableCellを追加し、TableRowTableに追加し、TableDocument オブジェクトに追加します。

// Create a second table cell by copying the OuterXml value of the first table cell.
TableCell tc2 = new TableCell(tc1.OuterXml);

// Append the table cell to the table row.
tr.Append(tc2);

// Append the table row to the table.
table.Append(tr);

if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null)
{
    throw new ArgumentNullException("MainDocumentPart and/or Body is null.");
}

// Append the table to the document.
doc.MainDocumentPart.Document.Body.Append(table);

サンプル コード

以下のコード例は、表を作成してそのプロパティを設定し、表のセルにテキストを挿入し、セルをコピーして、表をワープロ ドキュメントに挿入する方法を示しています。 メソッド CreateTable を呼び出すには、次の呼び出しを使用します。

string filePath = args[0];

CreateTable(filePath);

プログラムを実行した後、ファイルを検査して、挿入されたテーブルを確認します。

以下は、C# および Visual Basic の完全なサンプル コードです。

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;


// Insert a table into a word processing document.
static void CreateTable(string fileName)
{
    // Use the file name and path passed in as an argument 
    // to open an existing Word document.

    using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true))
    {
        // Create an empty table.
        Table table = new Table();

        // Create a TableProperties object and specify its border information.
        TableProperties tblProp = new TableProperties(
            new TableBorders(
                new TopBorder()
                {
                    Val =
                    new EnumValue<BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                new BottomBorder()
                {
                    Val =
                    new EnumValue<BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                new LeftBorder()
                {
                    Val =
                    new EnumValue<BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                new RightBorder()
                {
                    Val =
                    new EnumValue<BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                new InsideHorizontalBorder()
                {
                    Val =
                    new EnumValue<BorderValues>(BorderValues.Dashed),
                    Size = 24
                },
                new InsideVerticalBorder()
                {
                    Val =
                    new EnumValue<BorderValues>(BorderValues.Dashed),
                    Size = 24
                }
            )
        );

        // Append the TableProperties object to the empty table.
        table.AppendChild<TableProperties>(tblProp);

        // Create a row.
        TableRow tr = new TableRow();

        // Create a cell.
        TableCell tc1 = new TableCell();

        // Specify the width property of the table cell.
        tc1.Append(new TableCellProperties(
            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

        // Specify the table cell content.
        tc1.Append(new Paragraph(new Run(new Text("some text"))));

        // Append the table cell to the table row.
        tr.Append(tc1);

        // Create a second table cell by copying the OuterXml value of the first table cell.
        TableCell tc2 = new TableCell(tc1.OuterXml);

        // Append the table cell to the table row.
        tr.Append(tc2);

        // Append the table row to the table.
        table.Append(tr);

        if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null)
        {
            throw new ArgumentNullException("MainDocumentPart and/or Body is null.");
        }

        // Append the table to the document.
        doc.MainDocumentPart.Document.Body.Append(table);
    }
}