参考文章:https://blog.youkuaiyun.com/panhaigang123/article/details/82019193
Jacob下载地址:https://sourceforge.net/projects/jacob-project/
直达链接:https://sourceforge.net/projects/jacob-project/files/latest/download
文件解压后是这样:
1、需要将jacob*.dll文件复制到jre的bin目录下,类似:D:\Program Files\Java\jre1.8.0_144\bin
2、将jacob.jar文件复制到lib并添加依赖
代码:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordMerge {
/**
* @param fileList
* 合并多个word文档内容
* @param savepaths
* 合并保存新文档
*/
public static void mergeWordDataDoc(List<String> fileList, String savepaths) {
if (fileList.size() == 0 || fileList == null) {
return;
}
// 判断文件是否存在
if (new File(savepaths).exists()) {
try {
new File(savepaths).createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
new File(savepaths).delete();
} catch (Exception e) {
e.printStackTrace();
}
}
// 打开word
ActiveXComponent app = new ActiveXComponent("Word.Application");
try {
// 设置word不可见
app.setProperty("Visible", new Variant(false));
// 获得documents对象
Object docs = app.getProperty("Documents").toDispatch();
// 打开第一个文件
Object doc = Dispatch
.invoke((Dispatch) docs,
"Open",
Dispatch.Method,
new Object[] { (String) fileList.get(0),
new Variant(false), new Variant(true) },
new int[3]).toDispatch();
// 追加文件
for (int i = 1; i < fileList.size(); i++) {
Dispatch.invoke(app.getProperty("Selection").toDispatch(),
"insertFile", Dispatch.Method, new Object[] {
(String) fileList.get(i), "",
new Variant(false), new Variant(false),
new Variant(false) }, new int[3]);
}
// 保存新的word文件
Dispatch.invoke((Dispatch) doc, "SaveAs", Dispatch.Method,
new Object[] { savepaths, new Variant(1) }, new int[3]);
Variant f = new Variant(false);
Dispatch.call((Dispatch) doc, "Close", f);
} catch (Exception e) {
throw new RuntimeException("合并word文件出错.原因:" + e);
} finally {
app.invoke("Quit", new Variant[] {});
}
}
public static void main(String[] args) {
//1、手打word列表
List<String> filePathList = new ArrayList<>();
filePathList.add("d:\\test\\1.doc");
filePathList.add("d:\\test\\2.doc");
filePathList.add("d:\\test\\3.doc");
filePathList.add("d:\\test\\4.doc");
mergeWordDataDoc(filePathList, "d:\\merge.doc");
//2、自动读取目录下word
String path = "d:\\test";
File file = new File(path);
File[] files = file.listFiles();
List<String> list = new ArrayList<>();
for (File f : files) {
list.add(f.getAbsolutePath());
}
mergeWordDataDoc(list,"d:\\test\\merge.doc");
System.out.println("success");
}
}
可以手打word路径列表,也可以读取整个目录。