打开并向字处理文档添加文本

本主题演示如何使用 Open XML SDK for Office 中的类以编程方式打开Word处理文档并向其添加文本。


如何打开文档并在其中添加文本

Open XML SDK 可帮助你使用与元素对应的WordprocessingML强类型类创建Word处理文档结构和内容。 本主题演示如何使用 Open XML SDK 中的类打开Word处理文档并向其添加文本。 此外,本主题介绍文档的基本文档结构 WordprocessingML 、关联的 XML 元素及其相应的 Open XML SDK 类。


创建 WordprocessingDocument 对象

在 Open XML SDK 中WordprocessingDocument, 类表示Word文档包。 若要打开和使用Word文档,请从文档创建 类的WordprocessingDocument实例。 在基于文档创建实例后,您即可获得对包含文档文本的主文档部件的访问权限。 main文档部件中的文本在WordprocessingML包中使用标记表示为 XML。

若要从文档创建类实例,请调用方法之 Open 一。 提供了多个方法,每个方法都有不同的签名。 本主题中的示例代码使用 Open(String, Boolean) 具有需要两个参数的签名的方法。 第一个参数采用表示要打开的文档的完整路径字符串。 第二个 true 参数为 或 false ,表示是否希望打开文件进行编辑。 如果此参数为 false,则不会保存对文档所做的更改。

下面的代码示例调用 Open 方法。

// Open a WordprocessingDocument for editing using the filepath.
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true))
{

    if (wordprocessingDocument is null)
    {
        throw new ArgumentNullException(nameof(wordprocessingDocument));
    }

打开 Word 文档包后,您即可向主文档部件中添加文本。 若要访问main文档部件的正文,请创建任何缺少的元素并分配对文档正文的引用,如以下代码示例所示。

// Assign a reference to the existing document body.
MainDocumentPart mainDocumentPart = wordprocessingDocument.MainDocumentPart ?? wordprocessingDocument.AddMainDocumentPart();
mainDocumentPart.Document ??= new Document();
mainDocumentPart.Document.Body ??= mainDocumentPart.Document.AppendChild(new Body());
Body body = wordprocessingDocument.MainDocumentPart!.Document!.Body!;

WordProcessingML 文档的结构

文档的基本文档结构WordProcessingML由 和 body 元素组成document,后跟一个或多个块级元素(例如 p表示段落)。 段落包含一个或多个 r 元素。 r代表 run,它是具有一组通用属性(如格式设置)的文本区域。 运行包含一个或多个 t 元素。 元素 t 包含文本范围。 下面的代码示例演示 WordprocessingML 包含文本“示例文本”的文档的标记。

    <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
      <w:body>
        <w:p>
          <w:r>
            <w:t>Example text.</w:t>
          </w:r>
        </w:p>
      </w:body>
    </w:document>

使用 Open XML SDK,可以使用与元素对应的 WordprocessingML 强类型类创建文档结构和内容。 可以在 命名空间中找到 这些类。 下表列出了对应于 、、bodyrpt 元素的类的document类名。

WordprocessingML 元素 Open XML SDK 类 说明
<document/> Document 主文档部件的根元素。
<body/> Body 块级结构(如段落、表格、批注和 ISO/IEC 29500 规范中指定的其他项)的容器。
<p/> Paragraph 段落。
<r/> Run 一段连续文本。
<t/> Text 文本范围。

有关 WordprocessingML 文档的各个部分和元素的整体结构的详细信息,请参阅 WordprocessingML 文档的结构


生成用于添加文本的 WordprocessingML 标记

如果有权访问 main 文档部件的正文,请通过添加 、 RunText 类的Paragraph实例来添加文本。 这将生成必需的 WordprocessingML 标记。 下面的代码示例添加 段落。

// Add new text.
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(txt));

示例代码

此处所示的示例OpenAndAddTextToWordDocument方法可用于打开Word文档,并使用 Open XML SDK 追加一些文本。 若要调用此方法,请传递完整路径文件名作为第一个参数并传递要添加的文本作为第二个参数。

string file = args[0];
string txt = args[1];

OpenAndAddTextToWordDocument(args[0], args[1]);

以下是使用 C# 和 Visual Basic 编写的完整示例代码。

请注意, OpenAndAddTextToWordDocument 方法不包括对 Save的显式调用。 这是因为自动保存功能默认处于打开状态,并且未通过使用 OpenSettings在调用 Open 方法时禁用。

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

static void OpenAndAddTextToWordDocument(string filepath, string txt)
{
    // Open a WordprocessingDocument for editing using the filepath.
    using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true))
    {

        if (wordprocessingDocument is null)
        {
            throw new ArgumentNullException(nameof(wordprocessingDocument));
        }

        // Assign a reference to the existing document body.
        MainDocumentPart mainDocumentPart = wordprocessingDocument.MainDocumentPart ?? wordprocessingDocument.AddMainDocumentPart();
        mainDocumentPart.Document ??= new Document();
        mainDocumentPart.Document.Body ??= mainDocumentPart.Document.AppendChild(new Body());
        Body body = wordprocessingDocument.MainDocumentPart!.Document!.Body!;

        // Add new text.
        Paragraph para = body.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());
        run.AppendChild(new Text(txt));
    }
}

另请参阅