Apsoe关于获取word里面目录下面所有标题名称

我想获取一个word文档目录下面所有标题的名称,然后根据这些名称获取相对应的文本内容,如附件所示,test.doc是我的测试文档,expect.png是我的期望图片help.zip (21.0 KB)

@liyong199466,

如我们所见,MS Word将所有内容折叠到下一个较高的标题,例如,Heading1折叠特定节中的所有内容,因为它是最高的Heading.Heading 7是最低的标题。

我认为,您可以在以下代码上构建逻辑以获得所需的输出:

Document doc = new Document("E:\\207373\\test.doc");

ArrayList list = new ArrayList();
foreach (Paragraph para in doc.FirstSection.Body.Paragraphs)
{
    if (para.ParagraphFormat.StyleIdentifier == StyleIdentifier.Heading2)
    {
        list.Add(para);

        Node currentNode = para.NextSibling;
        bool isContinue = true;

        while (currentNode != null && isContinue)
        {
            if (currentNode.NodeType.Equals(NodeType.Paragraph))
            {
                Paragraph tempPara = (Paragraph)currentNode;
                if (tempPara.ParagraphFormat.StyleIdentifier == StyleIdentifier.Heading2 ||
                    tempPara.ParagraphFormat.StyleIdentifier == StyleIdentifier.Heading1)
                {
                    isContinue = false;
                    continue;
                }
            }

            list.Add(currentNode);
            currentNode = currentNode.NextSibling;
        }
    }
}

foreach (Node node in list)
{
    // do something with heading and paragraph nodes
}

doc.Save("E:\\207373\\20.1.docx");