views:

1119

answers:

1

Hi peeps,

I need to merge a whole bunch of docx files programatically. Imagine they are numbered 1 to 10. I essentially need a final.docx file that contains all 10 documents in it. If I can append the second to the first somehow, then I can repeat it for the third, then fourth, etc.

Note that I do NOT need to rebuild a table of contents or anything like that. Each docx just has some static content in it. However there ARE footers on these documents, and they need to be preserved.

Preferably an answer in C# or MSBuild.

Thanking you.

+2  A: 

Hi,

I had made an application in C# to merge RTF files into one doc,Iam hopeful it should work for DOC and DOCX files as well.

        Word._Application wordApp;
        Word._Document wordDoc;
        object outputFile = outputFileName;
        object missing = System.Type.Missing;
        object vk_false = false;
        object defaultTemplate = defaultWordDocumentTemplate;
        object pageBreak = Word.WdBreakType.wdPageBreak;
        string[] filesToMerge = new string[pageCounter];
        filestoDelete = new string[pageCounter];

        for (int i = 0; i < pageCounter; i++)
        {
            filesToMerge[i] = @"C:\temp\temp" + i.ToString() + ".rtf";
            filestoDelete[i] = @"C:\temp\temp" + i.ToString() + ".rtf";                
        }
        try
        {
            wordDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Word.Selection selection= wordApp.Selection;

        foreach (string file in filesToMerge)
        {
            selection.InsertFile(file,
                ref missing,
                ref missing,
                ref missing,
                ref missing);

            selection.InsertBreak(ref pageBreak);                                     
        }
        wordDoc.SaveAs(ref outputFile, ref missing, ref missing, ref missing, ref missing, ref missing,
               ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
               ref missing, ref missing);

Hope this helps!

Sumit Ghosh