在日常
工作中
,难免会遇到需要将多个
Word文档合并到一个文档中,对其进行重新整理的情况,为了能帮助大家高效快速的完成这个操作,
接下来
本文
就
将介绍
两种在
Java程序中
合并Word文档
的方法。
方法一:
如果需要被合并的文档默认
从新的一页开始显示
,我们可以
使用Document类中的insertTextFromFile方法将不同的文档合并到同一个文档。
方法二
:
如果需要
被合并的
文档承接上一个文档的最后一个段落末尾开始显示,则可以
先
获取第一个文档的最后一
个
section,然后将被合并文档的
段落
作为新的段落添加
到
section。
使用工具:
Free Spire.
Doc
for Java
(免费版)
Jar文件
导入方法
方法一:
下载
Free Spire.
Doc
for Java
包并解压缩
,
然后从lib文件夹下,
将
Spire.
Doc
.jar包
导入
到你的Java应用程序中。
(
导入成功
后
如下图所示
)
方法二:
通过
Maven仓库安装
导入
。
详细的操作步骤
请参考链接:
【
示例
1】被合并的文档默认
从新的一页开始显示
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);
}
}
生成文档:
【示例
2
】
被合并的
文档承接上一个文档的最后一个段落末尾开始显示
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 )document2.getSections()) {
for (DocumentObject obj:(Iterable )section.getBody().getChildObjects()
) {
lastSection.getBody().getChildObjects().add(obj.deepClone());
}
}
//保存文档
document1.saveToFile("Output.docx", FileFormat.Docx_2013);
}
}
生成文档: