Retrieve Style Names of all TextRanges in a Word Document in C#, VB.NET

Programmers may need to determine the style name of a section of text, or find the text in a document that appear in a specified style name, such as “Heading 1”. This article will show you how to retrieve style names that are applied in a Word document by using Spire.Doc with C# and VB.NET.

Step 1: Create a Document instance.

Document doc = new Document();

Step 2: Load a sample Word file.

doc.LoadFromFile("Sample.docx");

Step 3: Traverse all TextRanges in the document and get their style names through StyleName property.

foreach (Section section in doc.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        foreach (DocumentObject docObject in paragraph.ChildObjects)
        {
            if (docObject.DocumentObjectType == DocumentObjectType.TextRange)
            {
                TextRange text = docObject as TextRange;
                Console.WriteLine(text.StyleName);
            }                   
        }
    }                
}

Result:

Retrieve Style Names of all TextRanges in a Word Document in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
using System.Text.RegularExpressions;
namespace RetrieveStyleNames
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx");

            foreach (Section section in doc.Sections)
            {
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    foreach (DocumentObject docObject in paragraph.ChildObjects)
                    {
                        if (docObject.DocumentObjectType == DocumentObjectType.TextRange)
                        {
                            TextRange text = docObject as TextRange;
                            Console.WriteLine(text.StyleName);
                        }
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports System.Text.RegularExpressions
Namespace RetrieveStyleNames
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("Sample.docx")

			For Each section As Section In doc.Sections
				For Each paragraph As Paragraph In section.Paragraphs
					For Each docObject As DocumentObject In paragraph.ChildObjects
						If docObject.DocumentObjectType = DocumentObjectType.TextRange Then
							Dim text As TextRange = TryCast(docObject, TextRange)
							Console.WriteLine(text.StyleName)
						End If
					Next
					Console.WriteLine()
				Next
			Next
		End Sub
	End Class
End Namespace