C# / OpenXML 合并 Word 文档失败,已关闭。

3
我需要使用一个小型c#控制台应用程序合并多个word文档。目前为止一切都很好。这些文档是在arcplan中生成的。大约有30个文件被生成,但一些文档却损坏了,但仍然显示内容。 如果我现在合并所有正确的文件,我的文档就没问题。但如果我有一个损坏的文件在我的文件组中,任何一个损坏的文件都会生成空白页。我当然调试过了,但我没有看到任何解释空白页的问题。 参数如下: "C:\temp\Report_C_01.docx" "C:\temp\Report_D_01.docx" "C:\temp\Report_E_01.docx" 这是我的代码:
public static void Merge(params String[] filepaths)
    {
        String pathName = Path.GetDirectoryName(filepaths[0]);
        subfolder = Path.Combine(pathName, "Output\\"); //Wird für den gemergten File benötigt

        if (filepaths != null && filepaths.Length > 1)
        {
            WordprocessingDocument myDoc = WordprocessingDocument.Open(@filepaths[0], true); //Wordfiles werden geöffnet
            MainDocumentPart mainPart = myDoc.MainDocumentPart;

            for (int i = 1; i < filepaths.Length; i++)
            {
                String altChunkId = "AltChunkId" + i;
                AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                FileStream fileStream = File.Open(@filepaths[i], FileMode.Open);
                chunk.FeedData(fileStream);

                DocumentFormat.OpenXml.Wordprocessing.AltChunk altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk();
                altChunk.Id = altChunkId;
                //new page, if you like it...
                mainPart.Document.Body.AppendChild(new Paragraph(new Run(new Break() { Type = BreakValues.Page } )));
                //next document
                mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
            }
            mainPart.Document.Save();
            myDoc.Close();

            for (int i = 0; i < 1; i++)
            {
                String fileNameWE = Path.GetFileName(filepaths[i]);
                File.Copy(filepaths[i], subfolder + fileNameWE);
            }

            foreach (String fp in filepaths)
            {
                File.Delete(fp);
            }
        }
        else
        {
            Console.WriteLine("Nur 1 Argument");
        }
    }

希望有人可以帮助我。

最好的祝福 Christian


当您打开一个损坏的docx文件时,它是否会给您一个错误?我记得还会生成一个日志文件,提供有关问题的信息。或者没有错误,只是docx文件看起来很奇怪? - Jeremy Thompson
你应该尝试使用Package Explorer,因为它可以指出你的文档出了什么问题。 - Rubens Farias
当我在Word中打开它时,它会给我一个错误:“未知错误/word/document.xml第1行”,当我在生产力工具中查找时,我看到有3个未知元素,但如果我将其与未损坏的文件进行比较,则在XML树中看不到任何区别。文档打开后看起来很好。只是在我将其与我的程序合并后,它进入了一个空白页面。好的,我会用Package Explorer试一下,谢谢。 - Christian
不好意思,它没有帮助。XML 没问题,所以我不知道损坏是从哪里来的。 - Christian
1个回答

2

问题已经解决。似乎Word不能将不同格式的文档合并为一个。因此,如果您有两个带页脚的文档和其他三个没有页脚的文档,它就无法工作。显然,一些客户可能会遇到这种问题;至少代码是正确的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接