使用jacob合并多个word为单个word

1导入jar  包,我使用的是1.7,dil文件一定要和jar包匹配

 

使用前操作
    1、把dll文件放在%JAVA_HOME%\bin下(注意系统是32位还是64位),
    也可以放在C:\Windows\System32下,如果是64位应该放在C:\Windows\SysWOW64 下。建议放在jdk的bin目录下
    2、如果是在eclipse下开发,需要重新引入jdk(Preference/Java/Installed JREs)
    3、开发时将jacab.jar包放在项目lib下并add到liabraries中即可。

测试用例: 我在我两台电脑上都部署了,但不知为啥,一台运行出现异常

package com.dyz.test;

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 TestWord {

	public static void main(String[] args) {
		List list = new ArrayList();
		String file1 = "D:\\file1.doc";
		String file2 = "D:\\file2.doc";
		//String file3 = "D:\\file3.doc";
		list.add(file1);
		list.add(file2);
		//list.add(file3);
	//	System.out.println(System.getProperty("java.library.path"));
		uniteDoc(list, "d:\\file.doc");
	}

	public static void uniteDoc(List fileList, String savepaths) {
		if (fileList.size() == 0 || fileList == null) {
			return;
		}
		// 打开word
		ActiveXComponent app = new ActiveXComponent("Word.Application");// 启动word
		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[] {});
		}
	}

}

 

posted @ 2017-08-07 15:54  赤子之心_timefast  阅读(796)  评论(0编辑  收藏  举报