大家好!我是小寻
如果你想写一个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();
}
}
地震让大伙知道:居安思危,才是生存之道。