在 java 开发项目中,经常需要将多个 word 文档合并成一个完整文件,例如生成报告、合同汇总或文档归档。传统方式需要手动复制粘贴,不仅费时还容易出错。通过 spire.doc for java 库,我们可以轻松实现这一操作。它提供了直观的 api,支持两种常用合并方式:一种会在新页面插入完整文档,另一种则连续追加内容而不换页。
前提准备
首先在项目中引入 spire.doc for java 依赖(推荐使用 maven):
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupid>e-iceblue</groupid>
<artifactid>spire.doc</artifactid>
<version>14.3.1</version>
</dependency>
</dependencies>下载 jar 包后添加到 classpath 即可。代码中主要使用 com.spire.doc.* 包。
方法一:整文档插入(新页面开始)
适合需要清晰分页的场景。spire.doc 的 inserttextfromfile() 方法可直接将整个文档插入。
import com.spire.doc.*;
public class mergebyinsert {
public static void main(string[] args) {
// 加载主文档
document document = new document("input/sample1.docx");
// 依次插入其他文档(从新页面开始)
document.inserttextfromfile("input/sample2.docx", fileformat.docx_2013);
document.inserttextfromfile("input/sample3.docx", fileformat.docx_2013);
// 保存合并结果
document.savetofile("output/merged.docx", fileformat.docx_2013);
}
}
方法二:内容克隆追加(连续流式合并)
如果不想强制分页,可以克隆第二个文档的所有内容追加到第一个文档的末尾。适合保持统一格式的场景。
import com.spire.doc.*;
public class mergebyclone {
public static void main(string[] args) {
// 加载第一个文档作为基础
document maindoc = new document("input/sample1.docx");
// 支持合并多个文档
string[] files = {"input/sample2.docx", "input/sample3.docx"};
for (string file : files) {
document tempdoc = new document(file);
for (object secobj : (iterable) tempdoc.getsections()) {
section sec = (section) secobj;
for (object obj : (iterable) sec.getbody().getchildobjects()) {
documentobject item = (documentobject) obj;
// 追加到主文档最后一段
maindoc.getlastsection().getbody().getchildobjects().add(item.deepclone());
}
}
}
maindoc.savetofile("output/merged.docx", fileformat.docx_2013);
}
}
实用提示
- 错误处理:建议在加载文档前添加
try-catch捕获exception,并检查文件路径是否存在。 - 格式保留:两种方法均能较好保留原样式、表格、图片。如果需要更精细控制,可先获取
paragraph或table对象再追加。 - 批量合并:将文件路径放入列表或文件夹扫描,实现自动化处理。
- 性能:对于大文件,推荐分批处理或使用临时许可证移除评估水印。
通过以上代码,你可以在几分钟内完成合并功能,极大提升开发效率。实际项目中可封装成工具类,复用更方便。
到此这篇关于java借助spire.doc for java库合并word文档的文章就介绍到这了,更多相关java合并word文档内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论