Merge two Word documents

2

I have a problem and I would like a force, I have a project but I do not have any code to include my question.

The client is requesting a button that adds 2 or more .docx files and transforms it into 1 only or sends only 1 content.

I wanted to do this without API, because of my basic knowledge I know what to do in the word Inserting the object > and the content in the word properly opened, and as per the word is possible I believe that it would be necessary to use the reference Interopt.Word ... Has anyone had the same problem and solved it?

Note: I searched the site and there was only the .txt document doubt, I tried the same process but unfortunately it does not solve, the .docx file gets corrupted .

    
asked by anonymous 18.11.2015 / 16:32

1 answer

2

Ideally, you should do this using a library because .docx files are not simple text files, they are in a format called Office Open XML which is an XML-based file format.

On the libraries I did a search and found two that you might be interested in using:

  • Using Microsoft.Office.Interop.Word , which requires that Microsoft Word be installed. This library creates a Word instance to perform operations on top of a document, so it must be installed on the client machine.

  • Or used the DocX library, which manages to assemble Word documents without the need to have the program installed on the client machine.

If you choose to use Microsoft.Office.Interop.Word , take a look at in a question answer in Stack Overflow in English, it has an example of how to perform merge of Word documents.

To prevent this response from invalidating in the future I will put here the same solution that can be found in the link above:

The class:

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

namespace KeithRull.Utilities.OfficeInterop
{
  public class MsWord
  {
    /// <summary>
    /// This is the default Word Document Template file. I suggest that you point this to the location
    /// of your Ms Office Normal.dot file which is usually located in your Ms Office Templates folder.
    /// If it does not exist, what you could do is create an empty word document and save it as Normal.dot.
    /// </summary>
    private static 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.wdSectionBreakNextPage;
        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 missing
                                        , ref missing
                                        , ref missing
                                        , ref missing);

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

            //Count the number of documents to insert;
            int documentCount = filesToMerge.Length;

            //A counter that signals that we shoudn't insert a page break at the end of document.
            int breakStop = 0;

            // Loop thru each of the Word documents
            foreach (string file in filesToMerge)
            {
                breakStop++;
                // 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 && breakStop != documentCount)
                {
                    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);
        }
    }
  }
}

And the call:

using System;
using KeithRull.Utilities.OfficeInterop;

namespace WordDocMerge2
{
  class Program
  {
    static void Main(string[] args)
    {
        try
        {
            string document1 = @"D:\Visual Studio Projects.docx";
            string document2 = @"D:\Visual Studio Projects.docx";
            string document3 = @"D:\Visual Studio Projects.docx";

            string[] documentsToMerge = { document1, document2, document3 };

            string outputFileName = String.Format("D:\Visual Studio Projects\{0}.docx", Guid.NewGuid( ));

            MsWord.Merge(documentsToMerge, outputFileName, true);

        }
        catch (Exception ex)
        {
            //messageLabel.Text = ex.Message;
        }
    }
  }
}
    
18.11.2015 / 16:57