在平常工做中,不免會遇到須要將多個Word文檔合併到一個文檔中,對其進行從新整理的狀況,爲了能幫助你們高效快速的完成這個操做,接下來本文就將介紹兩種在Java程序中合併Word文檔的方法。html
方法一:若是須要被合併的文檔默認重新的一頁開始顯示,咱們能夠使用Document類中的insertTextFromFile方法將不一樣的文檔合併到同一個文檔。
方法二:若是須要被合併的文檔承接上一個文檔的最後一個段落末尾開始顯示,則能夠先獲取第一個文檔的最後一個section,而後將被合併文檔的段落做爲新的段落添加到section。java
使用工具:Free Spire.Doc for Java(免費版)maven
Jar文件導入方法
方法一:
下載Free Spire.Doc for Java包並解壓縮,而後從lib文件夾下,將Spire.Doc.jar包導入到你的Java應用程序中。(導入成功後以下圖所示)ide
方法二:
經過Maven倉庫安裝導入。詳細的操做步驟請參考連接:
https://www.e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html工具
【示例1】被合併的文檔默認重新的一頁開始顯示code
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class MergeWordDocument { public static void main(String[] args){ //獲取第一個文檔的路徑 String filePath1 = "文件1.docx"; //獲取第二個文檔的路徑 String filePath2 = "文件2.docx"; //加載第一個文檔 Document document = new Document(filePath1); //使用insertTextFromFile方法將第二個文檔的內容插入到第一個文檔 document.insertTextFromFile(filePath2, FileFormat.Docx_2013); //保存文檔 document.saveToFile("Output.docx", FileFormat.Docx_2013); } }
生成文檔:orm
【示例2】被合併的文檔承接上一個文檔的最後一個段落末尾開始顯示htm
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){ //加載第一個文檔 Document document1 = new Document(); document1.loadFromFile("文件1.docx"); //加載第二個文檔 Document document2 = new Document(); document2.loadFromFile("文件2.docx"); //獲取第一個文檔的最後一個section Section lastSection = document1.getLastSection(); //將第二個文檔的段落做爲新的段落添加到第一個文檔的最後一個section for (Section section:(Iterable <Section>)document2.getSections()) { for (DocumentObject obj:(Iterable <DocumentObject>)section.getBody().getChildObjects() ) { lastSection.getBody().getChildObjects().add(obj.deepClone()); } } //保存文檔 document1.saveToFile("Output.docx", FileFormat.Docx_2013); } }
生成文檔:blog