Get Paragraphs by Style Name in Word in C#, VB.NET

By using Spire.Doc, you can not only retrieve the style names of all paragraphs in a Word document, but also get the paragraphs with a specific style name. This is useful especially when you need to get the text in Title, Heading 1, Subtitle, etc.

Paragraph Style Names in Word Paragraph Style Names in Spire.Doc
Title Title
Heading 1 Heading1
Heading 2 Heading2
Heading 3 Heading3
Heading 4 Heading3
Subtitle Subtitle

Step 1: Load a sample Word file when initializing the Document object.

Document doc = new Document("sample.docx");

Step 2: Traverse the sections and paragraphs in the document and determine if the paragraph style name is "Heading1", if so, write the paragraph text on screen.

foreach (Section section in doc.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        if (paragraph.StyleName == "Heading1")
        {
            Console.WriteLine(paragraph.Text);
        }
    }
}

Output:

Get Paragraphs by Style Name in Word in C#, VB.NET

Full Code:

[C#]
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);
        }
    }
}
[VB.NET]
Dim doc As Document = New Document("sample.docx")
For Each section As Section In doc.Sections
    For Each paragraph As Paragraph In section.Paragraphs
        If paragraph.StyleName = "Heading1" Then
            Console.WriteLine(paragraph.Text)
        End If
    Next
Next