处理段落

本主题讨论 Open XML SDK Paragraph 类及其与 Open XML 文件格式 WordprocessingML 架构的关系。


WordprocessingML 中的段落

ISO/IEC 29500 规范中的以下文本介绍了用于表示 WordprocessingML 文档中的段落的 Open XML WordprocessingML 元素。

段落是 WordprocessingML 文档中块级内容的最基本单元,使用 <p> 元素进行存储。 段落定义在新行中开始的内容的明确分区。 段落可以包含三方面的信息:可选的段落属性、内嵌的内容(通常为连续文本)和用于比较两个文档的内容的一组可选修订 ID。

段落的属性通过 <pPr> 元素指定。 段落属性的一些示例包括对齐方式、边框、断字覆盖、缩进、行距、底纹、文本方向和孤行控制。

© ISO/IEC 29500:2016

下表列出了处理段落时使用的最常见 Open XML SDK 类。

WordprocessingML 元素 Open XML SDK 类
p Paragraph
pPr ParagraphProperties
r Run
t 文本

Paragraph 类

Open XML SDK Paragraph 类表示在上述 WordprocessingML 文档的 Open XML 文件格式架构中定义的 paragraph <p> 元素。 使用 Paragraph 对象可操作 WordprocessingML 文档中的各个 <p> 元素。

ParagraphProperties 类

在 WordprocessingML 中,段落的属性是通过段落属性 <pPr> 元素指定的。 段落属性的一些示例包括对齐方式、边框、断字覆盖、缩进、行距、底纹、文本方向和孤行控制。 OXML SDK ParagraphProperties 类表示 <pPr> 元素。

Run 类

字处理文档中的段落通常包含文本。 在 WordprocessingML 文档的 OXML 文件格式架构中,提供了 run <r> 元素来划分文本区域。 OXML SDK Run 类表示 <r> 元素。

Text 对象

<r>对于 元素,text <t> 元素是构成文档内容的文本的容器。 OXML SDK Text 类表示 <t> 元素。


Open XML SDK 代码示例

以下代码实例化 Open XML SDKParagraph 对象,然后使用它向 WordprocessingML 文档添加文本。

// <Snippet0>
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;


static void WriteToWordDoc(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();
        Body body = mainDocumentPart.Document.Body ?? mainDocumentPart.Document.AppendChild(new Body());

        // Add a paragraph with some text.
        Paragraph para = body.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());
        run.AppendChild(new Text(txt));
    }
}
// </Snippet0>

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

另请参阅

关于 Open XML SDK for Office

处理运行

如何:将样式应用于字处理文档中的段落

如何:打开字处理文档并在其中添加文本