How To: Merge Multiple Microsoft Word Documents in C#

.NET
May 23, 2007


“Combine. Merge. Join. Append. Concatenate. Microsoft Word Documents.”


I had a pretty laidback today because one of my projects was halted due some requirements issue(we have just finished phase 1 and the client already wants to start phase 2 but they dont know what the want yet) so i was assigned to help one of my colleagues in a problem that they were having in their project. The problem was that they were trying to merge multiple Microsoft Word Documents into one file and for some reason the solution that they have implemented was not doing the job. They had this function that reads bits and bytes of the document and then combines those bytes into a single file. Yikes!


Their solution was messy… really really messy.


After hearing the problem I quickly realized that I have already done this in one of the projects i had with a previous employer. I know that i had some notes somewhere about how i solved it so I immediately went to my Gmail and started looking and voila! I found just what i needed! I wrote this class as a solution to a similar problem and the big difference with my implementation from what my officemate had in their project is that I am using the Microsoft Office Interop Assemblies which in their case is a suitable solution since their application is a Windows app running on the users desktop(if this is a web app they might have a problem because i know server admins who doesn’t it when developers ask them to install MS Office to their production server).


Anyway, here’s the class in its entirety. I added comments to explain what the function is doing and should be self-explanatory since I did’nt do anything fancy on it.


using System;
using Word = Microsoft.Office.Interop.Word;

namespace KeithRull.Utilities.OfficeInterop
{
    public class MsWord
    {
        /// <summary>
        /// This is the default Word Document Template file
        /// </summary>
        private const string defaultWordDocumentTemplate = @”Normal.dot”;

        /// <summary>
        /// A function that merges Microsoft Word Documents that uses the default template
        /// </summary>
        /// <param name=”filesToMerge”>An array of files that we want to merge</param>
        /// <param name=”outputFilename”>The filename of the merged document</param>
        /// <param name=”insertPageBreaks”>Set to true if you want to have page breaks inserted after each document</param>
        public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks)
        {
            Merge(filesToMerge, outputFilename, insertPageBreaks, defaultWordDocumentTemplate);
        }

        /// <summary>
        /// A function that merges Microsoft Word Documents that uses a template specified by the user
        /// </summary>
        /// <param name=”filesToMerge”>An array of files that we want to merge</param>
        /// <param name=”outputFilename”>The filename of the merged document</param>
        /// <param name=”insertPageBreaks”>Set to true if you want to have page breaks inserted after each document</param>
        /// <param name=”documentTemplate”>The word document you want to use to serve as the template</param>
        public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
        {
            object defaultTemplate = documentTemplate;
            object missing = System.Type.Missing;
            object pageBreak = Word.WdBreakType.wdPageBreak;
            object outputFile = outputFilename;

            // Create  a new Word application
            Word._Application wordApplication = new Word.Application();

            try
            {
                // Create a new file based on our template
                Word._Document wordDocument = wordApplication.Documents.Add(
                                              ref defaultTemplate
                                            , ref missing
                                            , ref missing
                                            , ref missing);

                // Make a Word selection object.
                Word.Selection selection = wordApplication.Selection;

                // Loop thru each of the Word documents
                foreach (string file in filesToMerge)
                {
                    // Insert the files to our template
                    selection.InsertFile(
                                                file
                                            , ref missing
                                            , ref missing
                                            , ref missing
                                            , ref missing);

                    //Do we want page breaks added after each documents?
                    if (insertPageBreaks)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }
                }

                // Save the document to it’s output file.
                wordDocument.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);

                // Clean up!
                wordDocument = null;
            }
            catch (Exception ex)
            {
                //I didn’t include a default error handler so i’m just throwing the error
                throw ex;
            }
            finally
            {
                // Finally, Close our Word application
                wordApplication.Quit(ref missing, ref missing, ref missing);
            }
        }
    }
}


I gave them my file, showed them how to use it and save them the stress. Sweet! I hope this helps somebody in the future and if it does I hope they leave a comment too! Did you? 😛


You can download the .cs file here MsWord.cs (4.5 KB). Please do remember that you need to add a reference to Microsoft.Office.Core for this class to work.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.