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

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

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

Word元素 Open XML SDK类
p 段落
pPr ParagraphProperties
r 运行
t 文本

 

 

 

 

word元素可通过解压得到

Paragraph 类

Open XML SDK 2.5 Paragraph 类代表 paragraph (<p>) 元素,该元素在 WordprocessingML 文档的 Open XML 文件格式架构中定义,如上所述。 使用 Paragraph 对象,以操作 WordprocessingML 文档中的单个 <p> 元素。

ParagraphProperties 类

在 WordprocessingML 中,段落的属性通过 paragraph properties (<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 SDK  Paragraph 对象,然后使用它向 Word文档添加文本。

public static void WriteToWordDoc(string filepath, string txt)
    {
        // Open a WordprocessingDocument for editing using the filepath.
        using (WordprocessingDocument wordprocessingDocument =
             WordprocessingDocument.Open(filepath, true))
        {
            // Assign a reference to the existing document body.
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

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

  此代码运行时,以下 XML 会写入代码中引用的 Word 文档。

1 <w:p>
2       <w:r>
3         <w:t>String from WriteToWordDoc method.</w:t>
4       </w:r>
5     </w:p>

 

posted on 2018-08-30 17:56  天之梅子  阅读(669)  评论(0编辑  收藏  举报