程序员可能须要肯定一段文本的样式名称,或者找到文档中以指定样式名称出现的文本,例如“标题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
完整代码: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