JACOB的语法
转自:http://www.bitscn.com/pdb/java/200904/161117.html
如果你想写一个JAVA代码,其中需要调用JACOB提供的功能,而你还是新手,也许篇文章会大大降低你的花费时间。
我将一个关于JACOB的代码分成下面几个步骤:
1) ActiveXComponent ax = new ActiveXComponent("a1");//构建ActiveX组件实例
其中的a1的值和你需要调用的ActiveX控件有关
MS控件名 |
a1的值 |
InternetExplorer |
InternetExplorer.Application |
Excel |
Excel.Application |
Word |
Word.Application |
Powerpoint |
Powerpoint.Application |
vb/java Script |
ScriptControl |
windows media Player |
WMPlayer.OCX |
Outlook |
Outlook.Application |
Visio |
Visio.Application |
DAO |
DAO.PrivateDBEngine.35 |
MultiFace |
MultiFace.Face |
2) Dispatch ds = ax.getObject()。 toDispatch();//获取Dispatch对象,我们可以把每个Dispatch对象看成是对Activex控件的一个操作,这一步是获得该ActiveX控件的控制权。
(注:浅析JACOB 中提到过Variant类,这里的ax.getObject()便是获得该对象,我们将其转化为任何对象(类型))
3) Dispatch ds1 = Dispatch.get(ds, "a2")。toDispatch(); //获取该ActiveX对象数据结构中的a2属性
4) Dispatch d2 = Dispatch.invoke(ds1, "a3", a4, a5, a6)。toDispatch(); //功能调用,对ActiveX对象ds1的a3属性执行a4(Dispatch.Put\Dispatch.Get等)操作,执行后a3的值为a5,a6为错误参数码常定义为new int[1],(注:call、get和put方法都是通过该方法实现的)
5) Dispatch ds2 = Dispatch.put(ds, "a7","a8")。toDispatch();//将ActiveX对象ds的属性a4的值设置为a5,该方法返回类型同get一样
6) Dispatch ds3 = Dispatch.call(ds1, "a9", a10);//该方法和get方法非常类似,他是把a9属性赋值给a10
Ok其他的方法我觉得很容易理解,这里就不再做描述了。
下面是一个关于excel的代码,也许对您的进一步自学,会有好处
import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class ExcelDispatchTest { public static void main(String[] args) { ComThread.InitSTA(); ActiveXComponent xl = new ActiveXComponent("Excel.Application"); try { System.out.println("version=" + xl.getProperty("Version")); System.out.println("version=" + Dispatch.get(xl, "Version")); Dispatch.put(xl, "Visible", new Variant(true)); Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); Dispatch workbook = Dispatch.get(workbooks, "Add").toDispatch(); Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch(); Dispatch a1 = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] { "A1" }, new int[1]).toDispatch(); Dispatch a2 = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] { "A2" }, new int[1]).toDispatch(); Dispatch.put(a1, "Value", "123.456"); Dispatch.put(a2, "Formula", "=A1*2"); System.out.println("a1 from excel:" + Dispatch.get(a1, "Value")); System.out.println("a2 from excel:" + Dispatch.get(a2, "Value")); Variant f = new Variant(false); Dispatch.call(workbook, "Close", f); } catch (Exception e) { e.printStackTrace(); } finally { xl.invoke("Quit", new Variant[] {}); ComThread.Release(); } } |