在字处理文档中插入表

本主题演示如何使用 Open XML SDK for Office 中的类以编程方式将表插入字处理文档中。

获取 WordprocessingDocument 对象

若要打开现有文档,请实例化 类, WordprocessingDocument 如以下 using 语句所示。 在同一语句中,使用 Open 方法打开指定 filepath 处的字处理文件,并将布尔参数设置为 true ,以便启用文档编辑。

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

在 v3.0.0+ 中, Close() 已删除 方法,转而依赖于 using 语句。 它确保在 Dispose() 到达右大括号时自动调用 方法。 using 语句后面的块为 using 语句中创建或指定的对象设定范围。 WordprocessingDocument由于 Open XML SDK 中的 类会自动保存并关闭对象作为其IDisposable实现的一using部分,并且由于Dispose()在退出块时会自动调用,因此无需显式调用 Save()Dispose() ,只要使用 语句。

表格的结构

文档的基本文档结构WordProcessingML由 和 body 元素组成document,后跟一个或多个块级元素(例如 p表示段落)。 段落包含一个或多个 r 元素。 r 代表一段连续文本,它是具有一组共同属性(如格式设置)的文本区域。 运行包含一个或多个 t 元素。 元素 t 包含文本范围。文档可能包含一个表,如本示例所示。 表格 是在行 和列 中编排的一组段落(和其他块级内容)。 中的 WordprocessingML 表通过 tbl 元素定义,这类似于 HTML 表标记。 考虑一个空的单单元格表 (即具有一行、一列) 和四面 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>

此表使用 元素指定 100% 页面宽度的表范围属性、使用 tblWtblBorders 元素的一组表边框、使用 元素定义表中 tblGrid 的一组共享垂直边缘的表网格,以及使用 元素的 tr 单个表行。

示例代码的工作方式

在示例代码中,在 语句中 using 打开文档后,将创建一个新 Table 对象。 然后创建对象 TableProperties 并指定其边框信息。 类TableProperties包含采用 类型的OpenXmlElement数组的重载构造函数TableProperties()params。 代码使用此构造函数实例化具有TablePropertiesBorderType每个边框的对象,实例化每个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 属性,单元格内容 (“Hello, World!”使用 Text 对象 ) 。 在 Open XML Wordprocessing 架构中,段落元素 () <p\> 包含 run 元素 (<r\>) ,这些元素又包含文本元素 (<t\>) 。 若要使用 API 在表格单元格中插入文本,必须创建一个ParagraphRun对象,该对象包含一个Text对象,该对象包含要在单元格中插入的文本。 然后,将 Paragraph 对象追加到 对象 TableCell 。 这将创建适当的 XML 结构以便将文本插入到单元格。 TableCell然后将 追加到 对象。TableRow

// 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);

代码随后创建第二个表格单元格。 代码的最后一部分使用重载 TableCell 构造函数创建另一个表单元格,该构造函数 TableCell(String)OuterXml 现有 TableCell 对象的 属性作为其唯一参数。 创建第二个表单元格后,代码会将 TableCell 追加到 TableRow,并将 追加TableRowTableTable 对象。Document

// 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);
    }
}