In daily work, it is inevitable to encounter the situation that multiple Word documents need to be merged into one document and reorganized. In order to help you to complete this operation efficiently and quickly, this paper will introduce two methods of merging Word documents in Java programs.
Method 1: if the documents to be merged are displayed from a new page by default, we can use the insertTextFromFile method in the Document class to merge different documents into the same Document.
Method 2: if the merged document starts to display at the end of the last paragraph of the previous document, you can first obtain the last section of the first document, and then add the paragraphs of the merged document to the section as new paragraphs.
Use tools: Free Spire.Doc for Java (free version)
Jar file import method
Method 1:
Download and extract the free spirit.doc for java package, and then import the spirit.doc.jar package into your Java application from the lib folder. (see the figure below after importing successfully)
Method 2:
Import through Maven warehouse installation. Please refer to the link for detailed operation steps:
https://www.e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html
[example 1] the merged document is displayed from a new page by default
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class MergeWordDocument { public static void main(String[] args){ //Get the path to the first document String filePath1 = "Document 1.docx"; //Get the path to the second document String filePath2 = "Document 2.docx"; //Load first document Document document = new Document(filePath1); //Use the insertTextFromFile method to insert the contents of the second document into the first document document.insertTextFromFile(filePath2, FileFormat.Docx_2013); //Save document document.saveToFile("Output.docx", FileFormat.Docx_2013); } }
Generate document:
[example 2] the merged document starts to display at the end of the last paragraph of the previous 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){ //Load first document Document document1 = new Document(); document1.loadFromFile("Document 1.docx"); //Load second document Document document2 = new Document(); document2.loadFromFile("Document 2.docx"); //Get the last section of the first document Section lastSection = document1.getLastSection(); //Add the paragraph of the second document as a new paragraph to the last section of the first document for (Section section:(Iterable <Section>)document2.getSections()) { for (DocumentObject obj:(Iterable <DocumentObject>)section.getBody().getChildObjects() ) { lastSection.getBody().getChildObjects().add(obj.deepClone()); } } //Save document document1.saveToFile("Output.docx", FileFormat.Docx_2013); } }
Generate document: