【教程】Spire.Doc系列教程(8):C# 根据 Word 的标题样式获取文字

Spire.Doc支持获取Word文档中段落(Paragraph)和文本范围(TextRange)的样式,例如标题(Title)、标题1(Heading 1)、副标题(Subtitle)等。当然,我们也可以根据标题样式获取对应的文本。

Word段落样式名称 Spire.Doc中对应的样式名称
Title Title
Heading 1 Heading1
Heading 2 Heading2
Heading 3 Heading3
Heading 4 Heading3
Subtitle Subtitle

本文将展示如何从以下文档中获取2级标题对应的文本。

get-text-by-style-name-1

代码段:

//创建Document对象
Document doc = new Document();

//加载Word文档
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");

//遍历章节
foreach (Section section in doc.Sections)
{
    //遍历段落
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        //判断段落样式是否为Heading 2
        if (paragraph.StyleName == "Heading2")
        {
            //输出标题2对应的文本
            System.Console.WriteLine(paragraph.Text);
        }
    }
}

结果:

get-text-by-style-name-2

                                                                      【下载Spire.Doc最新试用版

猜你喜欢

转载自blog.csdn.net/weixin_43746001/article/details/88101826
今日推荐