java实现word文件合并
前言
本文使用了Free Spire.Office for Java这个工具,下面是官网地址
带Free的是免费版,功能较少,这个工具使用起来很方便。
一、Spire.Doc.jar
下载后将这个包导入库中,官网也有maven的导入方法,很方便
二、使用步骤
1.引入库
代码如下(示例):
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
2.写接口
代码如下:
/**
*
* @param filePath1 文件1,此为合并word时,放在前面的文件
* @param filePath2 文件2,此为合并word时,放在后面的文件
* @param filePath3 文件3,此为合并后保存的文件,可以与文件1、文件2地址相同,此时会覆原先的文件
* @return 返回一个map,state为状态码,200表示执行成功,其他情况表示失败,并返回msg
*/
public Map<String, Object> XXXXX(String filePath1, String filePath2, String filePath3) {
Map<String, Object> map = new HashMap<>();
map.put("state", "200");//代码执行结果,默认为200执行正常
try {
//因为调用的jar包把所有异常全部捕获了,所以需要提前判断两个文件是否存在
File file1 = new File(filePath1);
File file2 = new File(filePath2);
if (file1.exists() && file2.exists()) {
StopWatch stopWatch = new StopWatch();
stopWatch.start("合并文档所需时间");
//加载第一个文档
Document doc1 = new Document(filePath1);
//使用insertTextFromFile方法将第二个文档的内容插入到第一个文档
doc1.insertTextFromFile(filePath2, FileFormat.Docx_2013);
//保存文档
doc1.saveToFile(filePath3, FileFormat.Docx_2013);
stopWatch.stop();
Log4jUtils.getLogger().info(stopWatch.prettyPrint());
} else if (!file1.exists() && file2.exists()) {
map.put("state", "-1");
map.put("msg", "文件合并失败,目标文件不存在:" + filePath1);
Log4jUtils.getLogger().error("文件合并失败,目标文件不存在:" + filePath1);
return map;
} else if (file1.exists() && !file2.exists()) {
map.put("state", "-1");
map.put("msg", "文件合并失败,目标文件不存在:" + filePath2);
Log4jUtils.getLogger().error("文件合并失败,目标文件不存在:" + filePath2);
return map;
} else if (!file1.exists() && !file2.exists()) {
map.put("state", "-1");
map.put("msg", "文件合并失败,目标文件不存在:" + filePath1 + ",目标文件不存在:" + filePath2);
Log4jUtils.getLogger().error("文件合并失败,目标文件不存在:" + filePath1 + ",目标文件不存在:" + filePath2);
return map;
}
} catch (Exception e) {
map.put("state", "-1");
map.put("msg", "文件合并失败,相关文件1:" + filePath1 + ",相关文件2:" + filePath2);
Log4jUtils.getLogger().error("文件合并失败,相关文件1:" + filePath1 + ",相关文件2:" + filePath2);
e.printStackTrace();
}
return map;
}