本主题讨论 Open XML SDK Run 类及其与 Open XML 文件格式 WordprocessingML 架构的关系。
WordprocessingML 中的一段连续文本
ISO/IEC 29500(该链接可能指向英文页面) 规范中的以下文本介绍了 Open XML WordprocessingML 的连续文本元素。
下一级文档层次结构 [段落之后] 是一段连续文本,它定义具有一组常见属性的文本区域。 一段连续文本由 r 元素表示,这样创建器便可组合换行、样式或格式设置属性,从而将相同信息应用于一段连续文本的所有部分。
正如段落可具有属性一样,一段连续文本也可具有属性。 r 元素中的所有元素的属性由相应的可选 rPr 连续文本属性元素控制,这些元素必须是 r 元素的第一个子级。 反过来说,rPr 元素是应用于 r 元素的其余子级的一组属性元素的容器。 例如,通过 rPr 容器元素中的元素,使用者可控制以下 t 元素中的文本是否为加粗、带下划线或可见格式。 连续文本属性的一些示例包括粗体、边框、字符样式、颜色、字体、字号、斜体、字距调整、禁用拼写/语法检查、底纹、小号大写字母、删除线、文字方向和下划线。
© ISO/IEC 29500:2016
下表列出使用一段连续文本时使用的最常见 Open XML SDK 类。
XML 元素 | Open XML SDK 类 |
---|---|
p | 段落 |
rPr | RunProperties |
t | Text |
Run 类
Open XML SDK Run 类表示在 WordprocessingML 文档的 Open XML 文件格式架构中定义的 run <r>
元素,如上所述。 使用 Run 对象可操作 WordprocessingML 文档中的单个 <r>
元素。
RunProperties 类
在 WordprocessingML 中,使用 run properties 元素指定 run 元素的属性 <rPr>
。
连续文本属性的一些示例包括粗体、边框、字符样式、颜色、字体、字号、斜体、字距调整、禁用拼写/语法检查、底纹、小号大写字母、删除线、文字方向和下划线。
RunProperties使用 对象在 WordprocessingML 文档中设置运行的属性。
Text 对象
<r>
使用 元素时,文本 (<t>
) 元素是构成文档内容的文本的容器。 OXML SDK Text 类表示 <t>
元素。 使用 Text 对象可以在字处理文档中放置文本。
Open XML SDK 代码示例
以下代码可将文本添加到指定 WordprocessingML 文档的主文档图面。 Run 对象可区分段落中的文本区域,然后 RunProperties 对象用于对一段连续文本应用粗体格式。
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
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.
MainDocumentPart mainDocumentPart = wordprocessingDocument.MainDocumentPart ?? wordprocessingDocument.AddMainDocumentPart();
mainDocumentPart.Document ??= new Document();
Body body = mainDocumentPart.Document.Body ?? mainDocumentPart.Document.AppendChild(new Body());
// Add new text.
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
// Apply bold formatting to the run.
RunProperties runProperties = run.AppendChild(new RunProperties(new Bold()));
run.AppendChild(new Text(txt));
}
}
运行此代码时,以下 XML 会写入前面代码中指定的 WordprocessingML 文档。
<w:p>
<w:r>
<w:rPr>
<w:b />
</w:rPr>
<w:t>String from WriteToWordDoc method.</w:t>
</w:r>
</w:p>