使用Jacob操作Office 配置及结构简介
?
1、介绍
??? Jacob 是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁。使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。至于什么是COM组件,大家自己Google吧。
2、安装和配置
??? Jacob是一个开源软件,它的官方站点是:http://danadler.com/jacob/?大家可以到上面下载源代码研究,也可以直接下载编译后的二进制文件。
package jacobproject; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Variant; import com.jacob.com.Dispatch; public class Word { String strDir = "c:jacob_1.9"; String strInputDoc = strDir + "file_in.doc"; String strOutputDoc = strDir + "file_out.doc"; String strOldText = "[label:import:1]"; String strNewText = "I am some horribly long sentence, so long that [insert anything]"; boolean isVisible = true; boolean isSaveOnExit = true; public Word() { ActiveXComponent oWord = new ActiveXComponent("Word.Application"); oWord.setProperty("Visible", new Variant(isVisible)); Dispatch oDocuments = oWord.getProperty("Documents").toDispatch(); Dispatch oDocument = Dispatch.call(oDocuments, "Open", strInputDoc). toDispatch(); Dispatch oSelection = oWord.getProperty("Selection").toDispatch(); Dispatch oFind = oWord.call(oSelection, "Find").toDispatch(); Dispatch.put(oFind, "Text", strOldText); Dispatch.call(oFind, "Execute"); Dispatch.put(oSelection, "Text", strNewText); Dispatch.call(oSelection, "MoveDown"); Dispatch.put(oSelection, "Text", "nSo we got the next line including BR.n"); Dispatch oFont = Dispatch.get(oSelection, "Font").toDispatch(); Dispatch.put(oFont, "Bold", "1"); Dispatch.put(oFont, "Italic", "1"); Dispatch.put(oFont, "Underline", "0"); Dispatch oAlign = Dispatch.get(oSelection, "ParagraphFormat"). toDispatch(); Dispatch.put(oAlign, "Alignment", "3"); Dispatch oWordBasic = (Dispatch) Dispatch.call(oWord, "WordBasic"). getDispatch(); Dispatch.call(oWordBasic, "FileSaveAs", strOutputDoc); Dispatch.call(oDocument, "Close", new Variant(isSaveOnExit)); oWord.invoke("Quit", new Variant[0]); } public static void main(String[] args) { Word word = new Word(); } }?
4、jacob.jar的结构
jacob包括两个部分:
5、Jacob类
Jacob的结构很简单,包含以下几个类:
ComException Class:异常类
6、Jacob方法
用于访问COM/DLL对象的方法,读取、修改COM/DLL对象的属性。
setProperty method:属于ActiveXComponent类,设置属性值。
要注意一点:在使用Jacob时,很重要的一点是,用户必须安装有Office的应用程序。否则也就无法建立Java-COM桥,进而无法解析了。
文献出处:http://www.cnblogs.com/vulcans/archive/2009/09/08/1562588.html