Merge two Word documents

Asked

Viewed 287 times

2

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

Client is requesting a button that joins 2 or more. docx files and turns into 1 only or sends to 1 only content.

I wanted to do this without API, for my basic knowledge I know what to do in the word Inserting the object >> and the content in the word properly open, and as the word is possible I believe it would be necessary to use the reference Interopt.Word... Someone’s been through the same problem and solved it?

Note: I searched the site and there was only doubt of the document .txt, tried to perform the same process but unfortunately not fixed, the file .docx gets damaged.

  • You want to do it without using Interop.Word?

  • Just one detail, the [en.so] is not a forum

  • Using Interop.word, I guess who without it is not possible.

1 answer

2


The ideal would be for you to perform this procedure using a library, because files . docx are not simple text files, they are in a format called Office Open XML which is an XML-based file format.

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

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

  • Or used the library Docx, that can carry out the assembly of Word documents without the need to have the program installed in the client’s machine.

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

To prevent this answer from being invalidated 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\31.docx";
            string document2 = @"D:\Visual Studio Projects\33.docx";
            string document3 = @"D:\Visual Studio Projects\32.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;
        }
    }
  }
}
  • 1

    Very good guy, worked perfectly, thanks even!

  • I’m glad I could help you. :)

  • Beauty, tested and marked as an answer. The only problem is the formatting that has become unregulated, but that is no longer part of the question. Grateful for the response.

  • 1

    @Gabrielborghi o Keithrull.Utilities.Officeinterop is the namespace where the first class was set, you can change and put the one being used in your project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.