Christian
Christian

Reputation: 162

c# / openxml merge of word documents to one, fails --closed--

I have to merge several word documents with a small c# console application. So far so good. The documents are generated in arcplan. Around 30 files are generated, but somehow some documents are corrupted, but still shows me Content. If I merge now all files which are correct my document is fine but if i have a corrupted file in my bunch of files any corrupted generates an empty page. I debugged it of course, but i dont see anything going wrong which explains the empty page.

the arguments are like this: "C:\temp\Report_C_01.docx" "C:\temp\Report_D_01.docx" "C:\temp\Report_E_01.docx"

here´s my Code:

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");
        }
    }

Hope someone can help me.

Best regards Christian

Upvotes: 3

Views: 1266

Answers (1)

Christian
Christian

Reputation: 162

Fixed it. It seems word cannot merge different Formats in one Document. So if you have 2 documents with a footer and other 3 without it just won´t work. Obviously it can happen that some customers have these kind of issues; at least the Code is fine

Upvotes: 2

Related Questions