Spire.Doc支持获取Word文档中段落(Paragraph)和文本范围(TextRange)的样式,例如标题(Title)、标题1(Heading 1)、副标题(Subtitle)等。当然,我们也可以根据标题样式获取对应的文本。
Word 段落样式名称 | Spire.Doc 中对应的样式名称 |
Title | Title |
Heading 1 | Heading1 |
Heading 2 | Heading2 |
Heading 3 | Heading3 |
Heading 4 | Heading3 |
Subtitle | Subtitle |
本文将展示如何从以下文档中获取2级标题对应的文本。
C#
//创建Document对象
Document doc = new Document();
//加载Word文档
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
//遍历章节
foreach (Section section in doc.Sections)
{
//遍历段落
foreach (Paragraph paragraph in section.Paragraphs)
{
//判断段落样式是否为Heading 2
if (paragraph.StyleName == "Heading2")
{
//输出标题2对应的文本
System.Console.WriteLine(paragraph.Text);
}
}
}
VB.NET
'创建Document对象
Dim doc As Document = New Document
'加载Word文档
doc.LoadFromFile("C:\Users\Administrator\Desktop\sample.docx")
'遍历章节
For Each section As Section In doc.Sections
'遍历段落
For Each paragraph As Paragraph In section.Paragraphs
'判断段落样式是否为Heading 2
If (paragraph.StyleName = "Heading2") Then
'输出标题2对应的文本
System.Console.WriteLine(paragraph.Text)
End If
Next
Next
结果: