此案例需要用到jacob 下载地址 https://download.csdn.net/download/panhaigang123/10599733
将解压好的jacob放入如下图中
import java.io.File;
import java.util.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
* 合并多个word文档内容
* @author Administrator
*
*/
public class HbWordData {
/**
* @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) {
// 需要放到程序中可以运行;
List list = new ArrayList();
String file1= "D:\\test\\11.doc";
String file2= "D:\\test\\22.doc";
String file3= "D:\\test\\test.doc";
list.add(file1);
list.add(file2);
list.add(file3);
mergeWordDataDoc(list,"D:\\test\\n.doc");
System.out.println("success");
}
}