How To Split Or Merge Word Documents In Java

When you have a massive Word document to deal with, you can always split the document into small pieces and distribute them to multiple colleagues. After everyone has finished editing, all you need to do is merge these documents into a single document. To do so, you can effectively shorten the time limit for the project. In this article, I am going to introduce how to split or merge Word documents by using Spire.Doc for Java.
 

Add Spire.Doc.jar as dependency

 
If you create a Maven project, you can easily import the jar in your application using the following configurations. For non-Maven projects, please download the jar file from this link and manually add it as a dependency in your applicaition. 
  1. <repositories>  
  2.     <repository>  
  3.         <id>com.e-iceblue</id>  
  4.         <name>e-iceblue</name>  
  5.         <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>  
  6.     </repository>  
  7. </repositories>  
  8. <dependencies>  
  9.     <dependency>  
  10.         <groupId> e-iceblue </groupId>  
  11.         <artifactId>spire.doc</artifactId>  
  12.         <version>3.8.8</version>  
  13.     </dependency>  
  14. </dependencies>  

Example 1. Split document by section break

 
Spire.Doc provides the Document.getSectionsmethod, allowing programmers to easily access all sections within a document. Loop through these sections, get the specific one, and add its clone to a new document. The above steps will produce a sub-document.
 
Before you use this method to split document, make sure your document has multiple sections. Otherwise, it won’t work. In addition, Spire also supports splitting document by page break. If you’re interested, try it yourself.
  1. import com.spire.doc.Document;  
  2. public class SplitWordBySection {  
  3.     public static void main(String[] args) {  
  4.         //Create a Document object  
  5.         Document document = new Document();  
  6.         //Load a source document that contains multiple sections  
  7.         document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sections.docx");  
  8.         //Declare a new Document variable  
  9.         Document newWord;  
  10.         //Loop through sections in the source document  
  11.         for (int i = 0; i < document.getSections().getCount(); i++) {  
  12.             //Initialize the Document object  
  13.             newWord = new Document();  
  14.             //Copy the specific section from source document into new document  
  15.             newWord.getSections().add(document.getSections().get(i).deepClone());  
  16.             //Save the new document to the specified folder  
  17.             newWord.saveToFile(String.format("C:\\Users\\Administrator\\Desktop\\Output\\result-%d.docx", i));  
  18.         }  
  19.     }  
  20. }  
Output
 
How To Split Or Merge Word Documents In Java
 

Example 2. Merge documents by inserting content into a new page

 
When you merge one document into another, you may want the content to be added to a new page instead of the last paragraph of the parent document. The Document.insertTextFromFile method allows you to accomplish this job easily.
  1. import com.spire.doc.Document;  
  2. import com.spire.doc.FileFormat;  
  3. public class MergeDocuments {  
  4.     public static void main(String[] args) throws Exception {  
  5.         //Get the paths of the files that you want to merge  
  6.         String[] filePaths = new String[] {  
  7.             "C:\\Users\\Administrator\\Desktop\\Documents\\sample_1.docx",  
  8.             "C:\\Users\\Administrator\\Desktop\\Documents\\sample_2.docx",  
  9.             "C:\\Users\\Administrator\\Desktop\\Documents\\sample_3.docx"  
  10.         };  
  11.         //Create a Document object and load the first Word document  
  12.         Document document = new Document(filePaths[0]);  
  13.         //Loop through the rest documents  
  14.         for (int i = 1; i < filePaths.length; i++) {  
  15.             //Insert the certain document to the first document  
  16.             document.insertTextFromFile(filePaths[i], FileFormat.Docx_2013);  
  17.         }  
  18.         //Save the document  
  19.         document.saveToFile("C:\\Users\\Administrator\\Desktop\\MergedDocument.docx", FileFormat.Docx_2013);  
  20.     }  
  21. }  
Output
 
How To Split Or Merge Word Documents In Java
 

Example 3. Merge documents by inserting content behind the last paragraph

 
Apart from inserting content to a new page, you can insert content right behind the last paragraph of the previous document, so that the merged document appears to be continuous in content.
 
In the example 1,we already know how to access sections of a document. Under section, there is a more detailed division, which is child object. What we need to do is to get all the child objects of the current document and add them to the last section of the parent document. Remember to update the lastSection object dynamically, because each time we merge one document into the parent document, the lastSection changes. 
  1. import com.spire.doc.Document;  
  2. import com.spire.doc.DocumentObject;  
  3. import com.spire.doc.FileFormat;  
  4. import com.spire.doc.Section;  
  5. public class MergeDocuments {  
  6.     public static void main(String[] args) throws Exception {  
  7.         //Get the paths of the files that you want to merge  
  8.         String[] filePaths = new String[] {  
  9.             "C:\\Users\\Administrator\\Desktop\\sample_1.docx",  
  10.             "C:\\Users\\Administrator\\Desktop\\sample_2.docx",  
  11.             "C:\\Users\\Administrator\\Desktop\\sample_3.docx"  
  12.         };  
  13.         //Create a Document object and load the first Word document  
  14.         Document firstDocument = new Document(filePaths[0]);  
  15.         //Get last section of the first document  
  16.         Section lastSection = firstDocument.getLastSection();  
  17.         //Delare another document object  
  18.         Document otherDocument;  
  19.         //Loop through the rest documents  
  20.         for (int i = 1; i < filePaths.length; i++) {  
  21.             //Load the specific document  
  22.             otherDocument = new Document(filePaths[i]);  
  23.             //Loop through sections of a certain document  
  24.             for (Object section: otherDocument.getSections()) {  
  25.                 //Loop through child objects of a certain section  
  26.                 for (Object childObj: ((Section) section).getBody().getChildObjects()) {  
  27.                     //Add child object to the last section of the first document   
  28.                     lastSection.getBody().getChildObjects().add(((DocumentObject) childObj).deepClone());  
  29.                 }  
  30.             }  
  31.             //Update the lastSection object  
  32.             lastSection = lastSection.getDocument().getLastSection();  
  33.         }  
  34.         //Save the first document to another file  
  35.         firstDocument.saveToFile("C:\\Users\\Administrator\\Desktop\\MergedDocument.docx", FileFormat.Docx_2013);  
  36.     }  
  37. }  
Output
 
How To Split Or Merge Word Documents In Java
 
Thank you for taking the time to read this article. Happy coding!


Similar Articles