文檔半島外圍網上直營>>E-iceblue中文文檔>>在 C#、VB.NET 下檢索 Word 中所有 TextRanges 的樣式名稱
                在 C#、VB.NET 下檢索 Word 中所有 TextRanges 的樣式名稱
Spire.Doc for .NET是一款專門對 Word 文檔進行操作的 .NET 類庫。在于幫助開發人員無需安裝 Microsoft Word情況下,輕松快捷高效地創建、編輯、轉換和打印 Microsoft Word 文檔。擁有近10年專業開發經驗Spire系列辦公文檔開發工具,專注于創建、編輯、轉換和打印Word/PDF/Excel等格式文件處理,小巧便捷。下面我們將給您介紹如何在 C#、VB.NET 下檢索 Word 中所有 TextRanges 的樣式名稱
程序員可能需要確定一段文本的樣式名稱,或者在文檔中查找以指定樣式名稱出現的文本,例如“標題 1”。本文將向您展示如何使用 Spire.Doc 與 C# 和 VB.NET 檢索應用于 Word 文檔的樣式名稱。
第 1 步:創建一個 Document 實例。
Document doc = new Document();
第 2 步:加載示例 Word 文件。
doc.LoadFromFile("Sample.docx");
第 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);
}
}
}
}
結果:
  
 
完整代碼:
[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
以上便是如何在 C#、VB.NET 下檢索 Word 中所有 TextRanges 的樣式名稱,如果您有其他問題也可以繼續瀏覽本系列文章,獲取相關教程,你還可以給我留言或者加入我們的官方技術交流群。

 QQ交談
QQ交談 在線咨詢
在線咨詢 
                 
                
 渝公網安備
            50010702500608號
渝公網安備
            50010702500608號
             
            
 客服熱線
客服熱線