Java Combine Multiple Word Documents into One Single Word
Tags: java, word, combine, merge
Published: 2023-04-10 09:33:56

When creating reports or presentations, it can be beneficial to consolidate data from various sources into a single document. In order to produce a more comprehensive and lengthy document, it may be necessary to merge data from multiple separate Word documents into one cohesive file. In this article, you will learn how to combine two Word documents into one single Word document by using [Spire.Doc for Java](https://www.e-iceblue.com/Introduce/doc-for-java.html) from the following three parts:

- [Combine Two Word Document Files into one single Word] (#combine-documents-by-inserting-the-entire-file)
- [Merge Word Documents by Cloning Contents] (#merge-documents-by-cloning-contents)
- [Merge Word Documents with Additional Options] (#keep-the-original-format)

###Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded [from this link](https://www.e-iceblue.com/Download/doc-for-java.html). If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

```java
<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.3.11</version>
    </dependency>
</dependencies>
```
###Combine Documents by Inserting the Entire File
Spire.Doc for Java offers **Document.insertTextFromFile()** method to insert the entire contents of other documents into the desired document on a new page. The detailed steps of merging documents by inserting the entire file are as follows:

- Create an object of Document class and load a Word document from disk.
- Insert another Word document entirely to the loaded document using **Document.insertTextFromFile()** method.
- Save the result document using **Document.saveToFile()** method.

```java
import com.spire.doc.*;

public class merge {
    public static void main(String[] args) throws Exception {
        //Load the Word document
        Document doc = new Document();
        doc.loadFromFile("Sample1.docx");

        //Insert another Word document entirely to the document
        doc.insertTextFromFile( "Sample2.docx", FileFormat.Auto);

        //Save the document
        String output = "simpleInsertFile_out.docx";
        doc.saveToFile(output, FileFormat.Docx_2010);
        }
    }
```

![Merge](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wd456sbyjydf90wbt2i5.png)

###Merge Documents by Cloning Contents
In order to combine documents while maintaining the same style and without starting a new page, you can clone the contents of other documents and append them to the end of a document. The detailed steps of merging documents by cloning contents are as follows:

- Create two objects of Document and load the two Word documents from disk.
- Loop through the second document to get all the sections using **Document.getSections()** method, then loop through all the sections to get their child objects using **Section.getBod().getChildObjects()** method.
- Get the last section of the first document using **Document.getLastSection()** method, and then add the child objects to the last section of the first document using **Body.getChildObjects().add()** method.
- Save the result document using **Document.saveToFile()** method.

```java
import com.spire.doc.*;

public class deepClone {
    public static void main(String[] args) throws Exception {

        //Create two Document objects and load two Word documents from disk
        Document document1 = new Document();
        document1 .loadFromFile("Sample1.docx");
        Document document2 = new Document();
        document2.loadFromFile("Sample2.docx");

        //Loop through the second document to get all the sections
        for (Object sectionObj : (Iterable) document2.getSections()) {
            Section sec=(Section)sectionObj;
            //Loop through the sections of the second document to get their child objects
            for (Object docObj :(Iterable ) sec.getBody().getChildObjects()) {
                DocumentObject obj=(DocumentObject)docObj;

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

                //Add the child objects to the last section of the first document
                Body body = lastSection.getBody();
                body.getChildObjects().add(obj.deepClone());
            }
        }

        //Save the result document
        document1.saveToFile("MergingResult.docx", FileFormat.Docx_2013);
    }
}
```
![Deep Clone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hzr35vws1xbvyzl1jhu3.png)

###Keep the original format
When content is inserted or appended from another document, use **Document.setKeepSameFormat(true)** method to maintain the same formatting as the original document. Here comes to the steps.

- Create two objects of Document and load the two Word documents from disk.
- Keep the same format for the source document by setting **document1.setKeepSameFormat(true)**.
- Copy the sections of source document to destination document.
- Save the result document using **Document.saveToFile()** method.

```java
import com.spire.doc.*;

public class merge2 {
    public static void main(String[] args) throws Exception {

        //Initialize a new object of Document class and load the source document.
        Document document1 = new Document();
        document1.loadFromFile("Test.docx");

        //Initialize another object to load target document.
        Document document2 = new Document();
        document2.loadFromFile("Template_Docx_1.docx");

        //Keep same format of source document
        document1.setKeepSameFormat(true);

        //Copy the sections of source document to destination document
        for (Object sectionObj : document1.getSections()) {
            Section section=(Section)sectionObj;
            document2.getSections().add(section.deepClone());
        }

        //Save the result document
        document2.saveToFile("MergingResult2.docx", FileFormat.Docx_2013);
    }
}
```
![Keep the same format](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cip3a8p4wuxo9zhka78a.png)

###Conclusion

In this blog, we have demonstrated how to combine two Word documents into one single Word document using Java and Spire.Doc for java library. By following the steps outlined here, you can easily merge multiple Word documents and customize your final output. This technique can be useful for creating reports, generating reconciliations, or any other task that requires combining multiple sources of information into a single document. In addition to this, you can also use Spire.Doc for Java to split word documents into separate word document. In case you would have any queries, you can get help from[ Spire.Doc forums](https://www.e-iceblue.com/forum/spire-doc-f6.html).