(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類,設置屬性值。