通过使用Spire.Doc,您不仅可以检索Word文档中所有段落的样式名称,还可以获取具有特定样式名称的段落。这在您需要获取标题、标题 1、副标题等中的文本时尤其有用。
Spire.Doc 最新下载/product/3368/download
第 1 步:在初始化 Document 对象时加载示例 Word 文件。
Document doc = new Document("sample.docx");
第 2 步:浏览文档中的节和段落,判断段落样式名称是否为“Heading1”,如果是,则将段落文本写在屏幕上。
foreach (Section section in doc.Sections){foreach (Paragraph paragraph in section.Paragraphs){if (paragraph.StyleName == "Heading1"){Console.WriteLine(paragraph.Text);}}}
输出:
完整代码:
[C#]
using Spire.Doc;using Spire.Doc.Documents;using System;namespace GetParagh{class Program{static void Main(string[] args){Document doc = new Document("sample.docx");foreach (Section section in doc.Sections){foreach (Paragraph paragraph in section.Paragraphs){if (paragraph.StyleName == "Heading1"){Console.WriteLine(paragraph.Text);}}}}}}
[]
Imports Spire.DocImports Spire.Doc.DocumentsNamespace GetParaghClass ProgramPrivate Shared Sub Main(args As String())Dim doc As New Document("sample.docx")For Each section As Section In doc.SectionsFor Each paragraph As Paragraph In section.ParagraphsIf paragraph.StyleName = "Heading1" ThenConsole.WriteLine(paragraph.Text)End IfNextNextEnd SubEnd ClassEnd Namespace