Java 合并Word文档
在日常工作中,难免会遇到需要将多个Word文档合并到一个文档中,对其进行重新整理的情况,为了能帮助大家高效快速的完成这个操作,接下来本文就将介绍两种在Java程序中合并Word文档的方法。
方法一:如果需要被合并的文档默认从新的一页开始显示,我们可以使用Document类中的insertTextFromFile方法将不同的文档合并到同一个文档。
方法二:如果需要被合并的文档承接上一个文档的最后一个段落末尾开始显示,则可以先获取第一个文档的最后一个section,然后将被合并文档的段落作为新的段落添加到section。
使用工具:Free Spire.Docfor Java(免费版)
Jar文件导入方法
方法一:
下载Free Spire.Docfor Java包并解压缩,然后从lib文件夹下,将Spire.Doc.jar包导入到你的Java应用程序中。(导入成功后如下图所示)
方法二:
通过Maven仓库安装导入。详细的操作步骤请参考链接:
https://www.e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html
【示例1】被合并的文档默认从新的一页开始显示
importcom.spire.doc.Document;importcom.spire.doc.FileFormat;publicclassMergeWordDocument{publicstaticvoidmain(String[]args){//获取第一个文档的路径StringfilePath2="文件1.docx";//获取第二个文档的路径StringfilePath3="文件2.docx";//加载第一个文档Documentdocument=newDocument(filePath2);//使用insertTextFromFile方法将第二个文档的内容插入到第一个文档document.insertTextFromFile(filePath3,FileFormat.Docx_2013);//保存文档document.saveToFile("Output.docx",FileFormat.Docx_2013);}}
生成文档:
【示例2】被合并的文档承接上一个文档的最后一个段落末尾开始显示
importcom.spire.doc.Document;importcom.spire.doc.DocumentObject;importcom.spire.doc.FileFormat;importcom.spire.doc.Section;publicclassMergeWordDocument{publicstaticvoidmain(String[]args){//加载第一个文档Documentdocument1=newDocument();document1.loadFromFile("文件1.docx");//加载第二个文档Documentdocument2=newDocument();document2.loadFromFile("文件2.docx");//获取第一个文档的最后一个sectionSectionlastSection=document1.getLastSection();//将第二个文档的段落作为新的段落添加到第一个文档的最后一个sectionfor(Sectionsection:(Iterable<Section>)document2.getSections()){for(DocumentObjectobj:(Iterable<DocumentObject>)section.getBody().getChildObjects()){lastSection.getBody().getChildObjects().add(obj.deepClone());}}//保存文档document1.saveToFile("Output.docx",FileFormat.Docx_2013);}}
生成文档:
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。