本文将介绍通过使用Spire.Doc for .NET根据段落标题样式名称来读取Word中相应段落的方法。
C#
//创建Document对象,并加载测试文档
Document doc = new Document();
doc.LoadFromFile("sample.doc");
//实例化StringBuilder对象
StringBuilder sb = new StringBuilder();
//遍历文档
foreach (Section section in doc.Sections)
{
foreach (Paragraph paragraph in section.Paragraphs)
{
//判断段落标题名称
if (paragraph.StyleName == "Heading1")
{
sb.AppendLine(paragraph.Text);
}
if (paragraph.StyleName == "Heading2")
{
sb.AppendLine(paragraph.Text);
}
if (paragraph.StyleName == "Heading3")
{
sb.AppendLine(paragraph.Text);
}
if (paragraph.StyleName == "Heading4")
{
sb.AppendLine(paragraph.Text);
}
}
}
//将符合标题名称的段落写入.txt文档
File.WriteAllText("Extract.txt", sb.ToString());
VB.NET
'创建Document对象,并加载测试文档
Dim doc As Document = New Document
doc.LoadFromFile("sample.doc")
'实例化StringBuilder对象
Dim sb As StringBuilder = New StringBuilder
'遍历文档
For Each section As Section In doc.Sections
For Each paragraph As Paragraph In section.Paragraphs
'判断段落标题名称
If (paragraph.StyleName = "Heading1") Then
sb.AppendLine(paragraph.Text)
End If
If (paragraph.StyleName = "Heading2") Then
sb.AppendLine(paragraph.Text)
End If
If (paragraph.StyleName = "Heading3") Then
sb.AppendLine(paragraph.Text)
End If
If (paragraph.StyleName = "Heading4") Then
sb.AppendLine(paragraph.Text)
End If
Next
Next
'将符合标题名称的段落写入.txt文档
File.WriteAllText("Extract.txt", sb.ToString)
读取结果: