Merge Word Documents in Java

This article demonstrates how to merge Word documents using Spire.Doc for Java.

Document class provides an insertTextFromFile() method that let us merge Word documents by inserting content from a source document into a destination document. In the result document, the inserted content will start from a new page.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class MergeWordDocument {
    public static void main(String[] args){

        //File path of the first document
        String filePath1 = "merge1.docx";
        //File path of the second document
        String filePath2 = "merge2.docx";

        //Load the first document
        Document document = new Document(filePath1);

        //Insert content of the second document into the first document
        document.insertTextFromFile(filePath2, FileFormat.Docx_2013);

        //Save the resultant document
        document.saveToFile("Output.docx", FileFormat.Docx_2013);       

    }
}

Output:

Merge Word Documents in Java

If you want the inserted content to follow the last paragraph of the destination document instead of starting from a new page, use the below method to clone sections of the source document and then append to the last section of the destination document.

import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;

public class MergeWordDocument {
    public static void main(String[] args){

        //File path of the first document
        String filePath1 = "merge1.docx";
        //File path of the second document
        String filePath2 = "merge2.docx";

        //Load the first document
        Document document1 = new Document(filePath1);
        //Load the second document
        Document document2 = new Document(filePath2);

        //Get the last section of the first document
        Section lastSection = document1.getLastSection();

        //Add the sections of the second document to the last section of the first document
        for (Section section:(Iterable )document2.getSections()) {
            for (DocumentObject obj:(Iterable )section.getBody().getChildObjects()
                 ) {
                lastSection.getBody().getChildObjects().add(obj.deepClone());
            }
        }

        //Save the resultant document
        document1.saveToFile("Output.docx", FileFormat.Docx_2013);

    }
}

Output:

Merge Word Documents in Java