Word控件Spire.Doc 教程:在C#,VB.NET的Word中检索所有TextRanges样式名称

程序员可能需要确定一段文本的样式名称,或者找到文档中以指定样式名称出现的文本,例如“标题1”。本文将展示如何在C#和VB.NET中使用Spire.Doc来检索应用于Word文档的样式名称。

Step 1: 创建一个文档实例。

Document doc = new Document();

Step 2: 加载一个示例Word文件。

doc.LoadFromFile("Sample.docx");

Step 3: 遍历文档中的所有TextRanges,并通过StyleName属性获取样式名称。

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);
            }                   
        }
    }                
}

结果:

Word控件Spire.Doc 教程:在C#,VB.NET的Word中检索所有TextRanges样式名称

完整代码:

[C#]

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]

Document doc = New Document()
doc.LoadFromFile("Sample.docx")
 
Dim section As Section
For Each section In doc.Sections
    Dim paragraph As Paragraph
    For Each paragraph In section.Paragraphs
        Dim docObject As DocumentObject
        For Each docObject In paragraph.ChildObjects
            If docObject.DocumentObjectType = DocumentObjectType.TextRange Then
                Dim text As TextRange = docObject as TextRange
                Console.WriteLine(text.StyleName)
            End If
        Next
        Console.WriteLine()
    Next
Next

转载于:https://my.oschina.net/u/3006003/blog/1595596