合并Word文档是指将多个Word文档的内容、款式和格局合并成一个新的Word文档。这个性能通常在须要整合多个文档内容时应用,比方在对多个人员提交的文档进行汇总、审阅或编辑时。通过合并Word文档,能够大大提高工作效率,缩小手动复制粘贴等繁琐操作,同时保留原始文档的格局和款式,使得最终生成的合并文档看起来更加标准、好看。本文将介绍如何通过Free Spire.Doc for Java组件来合并Word文档。上面是具体方法和示例代码。
程序环境:
IntelliJ IDEA 2018 (jdk 1.8.0)
在进行操作之前先导入jar包,请参考以下两种导入形式:
办法一:如果应用的是 maven,能够增加以下代码到我的项目的 pom.xml 文件中。
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.cn/repository/maven-public/</url> </repository></repositories><dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc.free</artifactId> <version>5.2.0</version> </dependency></dependencies>
办法二:如果没有应用 maven,则能够从此链接下载Free Spire.Doc for Java,找到lib文件夹下的Spire.doc.jar并进行解压;而后在IDEA中创立一个新我的项目,顺次点击“文件”(File),“我的项目构造”(Project Structure),“组件”(Modules),“依赖项”(Dependencies),再点击右方绿色“+”下的第一个选项“jar文件或门路”(JARs or Directories),找到解压后的Spire.doc.jar 文件,点击确认,将其导入到我的项目中。
通过插入文档来合并文档
这一办法是指在文档最初,新起一页插入另外的文档。
办法步骤:
- 创立Document类的对象并加载一个示例文档。
- 应用 Document.insertTextFromFile()办法将另一个 Word 文档齐全插入到加载的该文档。
应用Document.saveToFile()办法保留后果文档。
例代码:
import com.spire.doc.*;public class merge { public static void main(String[] args) { //创立Document对象并加载一个示例文档 Document document = new Document("sample1.docx"); //将另一个Word文档齐全插入到文档中 document.insertTextFromFile("sample2.docx", FileFormat.Docx_2013); //保留后果文档 document.saveToFile("result1.docx", FileFormat.Docx_2013); }}
通过复制内容来合并文档
这一办法是指将文档内容插入到指定文档最初,不另起一页。
办法步骤:
- 创立两个Document对象并加载两个示例文档。
- 遍历第二个文档,通过Document.getSections()办法获取所有节。
- 遍历所有节,通过Section.getBod().getChildObjects()办法以获取其子对象。
- 应用 Document.getLastSection()办法获取第一个文档的最初一节。
- 应用Body.getChildObjects().add()办法将子对象增加到第一个文档的最初一节中。
应用Document.saveToFile()办法保留后果文档。
示例代码:
import com.spire.doc.*;public class mergeDocuments { public static void main(String[] args){ //创立两个Document对象并加载两个示例文档 Document document1 = new Document("sample1.docx"); Document document2 = new Document("sample2.docx"); //遍历第二个文档,获取所有节 for (Object sectionObj : (Iterable) document2.getSections()) { Section sec=(Section)sectionObj; //遍历第二个文档的所有节,获取其子对象 for (Object docObj :(Iterable ) sec.getBody().getChildObjects()) { DocumentObject obj=(DocumentObject)docObj; //获取第一个文档的最初一节 Section lastSection = document1.getLastSection(); //将子对象增加到第一个文档的最初一节中 Body body = lastSection.getBody(); body.getChildObjects().add(obj.deepClone()); } } //保留后果文档 document1.saveToFile("result2.docx", FileFormat.Docx_2013); }}