OpenXML - 使用 altChunk 元素计算文档中的段落数

问题描述 投票:0回答:1

我正在尝试使用 OpenXML 计算 Word 文档中的段落数或运行数。对于简单的文档,可以通过以下方式完成:

using (WordprocessingDocument document = WordprocessingDocument.Open(file, false))
{                  
    var paragraphs = document.MainDocumentPart.Document.Body.
       Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>();

    int numberOfParagraphs  = paragraphs.ToArray().Length;

    var runs = document.MainDocumentPart.Document.Body.
        Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>();
    
    int numberOfRuns  = runs.ToArray().Length;
}

但是我在处理使用 AltChunks 合并小文档创建的文档时遇到了麻烦。返回的值是错误的并且太低了。所以我认为我遗漏了全部或部分段落或大块的运行。

关于如何计算 AltChunk 中的段落或运行元素有什么想法吗?我尝试查看每个 AltChunk 中的后代,但我得到 0。

我有一个想法,如果我将每个 AltChunk 转换为文档,我就能够进行计数,但是当我向其传递 AltChunk 时,WordprocessingDocument.Open 方法不起作用。

任何想法将不胜感激。

c# count ms-word openxml
1个回答
0
投票

mainDocumentPart 将保存所有原始段落和 altChunk。您需要迭代 altChunk 才能知道每个 altChunk 有多少个段落。

以下代码对我有用:

static void Main(string[] args)
{
    string fileName1 = @"Destination.docx";
    string fileName2 = @"Source.docx";
    string testFile = @"Test.docx";
    File.Delete(fileName1);
    File.Copy(testFile, fileName1);
    using (WordprocessingDocument myDoc =
        WordprocessingDocument.Open(fileName1, true))
    {
        string altChunkId = "AltChunkId1";
        MainDocumentPart mainPart = myDoc.MainDocumentPart;
        AlternativeFormatImportPart chunk =
            mainPart.AddAlternativeFormatImportPart(
            AlternativeFormatImportPartType.WordprocessingML, altChunkId);
        using (FileStream fileStream = File.Open(fileName2, FileMode.Open))
            chunk.FeedData(fileStream);
        AltChunk altChunk = new AltChunk();
        altChunk.Id = altChunkId;
        mainPart.Document
            .Body
            .InsertAfter(altChunk, mainPart.Document.Body
            .Elements<Paragraph>().Last());
        mainPart.Document.Save();

        // Counting paragraphs

        int paragraphCount = 0;

        paragraphCount += mainPart.Document.Body.Elements<Paragraph>().Count();
        var altChunks = mainPart.Document.Body.Descendants<AltChunk>().ToList();
        foreach (var aChunk in altChunks)
        {
            paragraphCount += aChunk.Parent.Elements<Paragraph>().Count();
        }

        Console.WriteLine("Paragraph Count:: {0}", paragraphCount);
        Console.ReadLine();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.