C# Aspose 对Word文档的操作

怎样使用aspose得到各级标题,得到标题下有多少表格,并得到表格的序号

更新了下代码,非嵌套统计正确

img

using System;
using System.Collections.Generic;
using System.Linq;
using Aspose.Words;

namespace Aspose.Words
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document(@"C:\Users\Admin\Desktop\t.docx");
            var tableCountTotal = 0;


            var ps = doc.GetChildNodes(NodeType.Paragraph, true);
            foreach(Paragraph p in ps)
            {
                if (p.ParagraphFormat.StyleIdentifier == StyleIdentifier.Heading2)
                {
                    var text = p.GetText().Trim();//去掉收尾空格,要不有\r打印后不显示内容,-_-||。。

           
                    //统计h2标题后的table数量
                    var count = 0;
                    Node node = p.NextSibling;
                     if (node != null)
                         do
                         {
                             if (node.NodeType == NodeType.Table) count++;
                             node = node.NextSibling;
                             if (node == null//没有下个节点
                                 ||
                                 (//碰到下一个标题2退出table统计
                                 node.NodeType == NodeType.Paragraph
                                 && ((Paragraph)node).ParagraphFormat.StyleIdentifier == StyleIdentifier.Heading2
                                 )
                                 )
                                 break;
                         }
                         while (true);

                     tableCountTotal += count;

                    Console.WriteLine(text + "下有"+count+"个表格");
                }

            }
            Console.WriteLine("总共有个表格:" + tableCountTotal + "\n");
            Console.WriteLine("H2-1\r测试");//H2-1没显示。。。还以为代码有问题了。。-_-||
            Console.ReadKey();
        }
    }
}

API参考,DOM模型


img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632