Jacob 是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁。使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。Jacob下载的地址为:
http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368
配置:
(1)将解压包中的jacob.dll(x86常用,x64)拷到windows安装路径下的WINDOWS\system32文件夹下
(2)将jacob.jar文件拷到classpath下即可
(3)检查一下计算机中是否安装office,如果没安装则要安装,因为无论是使用Jacob操作Word还是Excel都需要office支持的!
常见的问题
Exception in thread "main" java.lang.UnsatisfiedLinkError: no jacob in java.library.path
出现上面异常是因为没有dll文件
com.jacob.com.ComFailException: Invoke of: Open
Source: Microsoft Office Word
出现上面异常是因为文件路径不正确
cant get Object cldid from progid
出现上面的异常是因为机器上没安装word
写了一小段代码,用来替换word文档中的文字,粘出来与大家分享!
package test; import com.jacob.com.*; import com.jacob.activeX.*; public class aa { public static void main(String[] args) { ActiveXComponent app = new ActiveXComponent("Word.Application"); //启动word String inFile = "D:\\template.doc"; //要替换的word文件 try { app.setProperty("Visible", new Variant(false)); //设置word不可见 Dispatch docs = app.getProperty("Documents").toDispatch(); Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method, new Object[] { inFile, new Variant(false),new Variant(false) }, new int[1]).toDispatch(); //打开word文件,注意这里第三个参数要设为false,这个参数表示是否以只读方式打开, //因为我们要保存原文件,所以以可写方式打开。 Dispatch selection = app.getProperty("Selection").toDispatch();//获得对Selection组件 Dispatch.call(selection, "HomeKey", new Variant(6));//移到开头 Dispatch find = Dispatch.call(selection, "Find").toDispatch();//获得Find组件 Dispatch.put(find, "Text", "name"); //查找字符串"name" Dispatch.call(find, "Execute"); //执行查询 Dispatch.put(selection, "Text", "111"); //替换为"111" Dispatch find1 = Dispatch.call(selection, "Find").toDispatch();//获得Find组件 Dispatch.call(selection, "HomeKey", new Variant(6));//移到开头 Dispatch.put(find1, "Text", "8位随机生成密码"); //查找字符串 Dispatch.call(find1, "Execute"); //执行查询 Dispatch.put(selection, "Text", "222"); String newFileName = "D:\\temp.doc"; Dispatch.call(doc, "SaveAs",newFileName); //另存文件 Dispatch.call(doc, "Close", new Variant(false)); System.out.println("is over"); } catch (Exception e) { e.printStackTrace(); }finally{ app.invoke("Quit",new Variant[]{}); app.safeRelease(); } } }