Word控件Spire.Doc 教程:在C#,VB.NET的Word中檢索全部TextRanges樣式名稱

程序員可能須要肯定一段文本的樣式名稱,或者找到文檔中以指定樣式名稱出現的文本,例如「標題1」。本文將展現如何在C#和VB.NET中使用Spire.Doc來檢索應用於Word文檔的樣式名稱。程序員

Step 1: 建立一個文檔實例。blog

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

結果:get

圖片1

完整代碼:it

[C#]io

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]foreach

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
相關文章
相關標籤/搜索