(1)jacob是个什么玩意?
jacob一个Java-COM中间件,用java去操纵office;主要包括jacob-1.18-x64.dll 、jacob.jar
(2)Jacob 主要对象
- ActiveXComponent Class:初始化word窗口对象,Microsoft Office Word 程序对象
- Dispatch Class:用于指向封装后的MS数据结构。常用的方法有call,subcall,get,invoke…后面会介绍使用方法。
- 包括document /documents/selection/range/font
- Variant Class:用于映射COM的Variant数据类型。提供Java和COM的数据交换
(3)Jacob方法
- call method:
方法名Open(打开文档):Dispatch.call(documents, "Open", “文档”).toDispatch()。
add(新文档):Dispatch.call(documents, "Add").toDispatch()
Find(查找文本):Dispatch.call(this.selection, "Find").toDispatch()
- get method:读取COM对象的属性值,返回一个Variant类型值。
- put method:设置COM对象的属性值。
(1)查找文本并替换
Dispatch find = Dispatch.call(this.selection, "Find").toDispatch();
// 设置要查找的?热?br />
Dispatch.put(find, "Text", toFindText);//查找文本并替换
(2)设置字体
Dispatch font = Dispatch.get(getSelection(), "Font").toDispatch();
Dispatch.put(font, "Name", new Variant(“宋体”));
- invoke method:call的另一种用法,更复杂一些。可以用来调用自定义的宏命令
Dispatch.call(this.section, "insertPaper")
程序退出word.invoke("Quit", new Variant[0]);
文档另存为Dispatch.invoke(this.document, "SaveAs", Dispatch.Method, new Object[] { htmlFile, new Variant(10) }, new int[1])
-
文档插入Dispatch.invoke(selection, "InsertFile", Dispatch.Method, new Object[] { htmlFile, "", new Variant(false), new Variant(false), new Variant(false) }, new int[3]);
- getProperty method:属于ActiveXComponent类,读取属性值,返回一个Variant类型值。this.selection = word.getProperty("Selection").toDispatch();
- setProperty method:属于ActiveXComponent类,设置属性值。