一、準備工作
JACOB就是JAVA-COM Bridge的縮寫,提供自動化的訪問com的功能,也是透過JNI功能訪問windows平臺下的com元件或者win32系統庫的。
參考 : http://danadler.com/jacob/
二、安裝Jacob
Jacob的安裝非常的簡單,我們解開下載的jacob-1.15-M2.zip,在文件夾中找到jacob-1.15-M2-x64.dll、jacob-1.15-M2-x86.dll和jacob.jar三個文件。
jacob-1.15-M2-x64.dll、jacob-1.15-M2-x86.dll:
1. 放到系統的system32檔夾下就行了,連註冊都不用的。
2. 拷貝到jdk或者jre的bin目錄下也行,當前測試檔所在的目錄也行,就是只要在 java.library.path中就可以。
jacob.jar: 設置到classpath中去就可以了。
三、實例演示
import com.ms.com.*;
import com.ms.activeX.*;
public class DispatchTest{
public static void main(String[] args){
ActiveXComponent xl = new ActiveXComponent("Excel.Application");
Object xlo = xl.getObject();
try {
System.out.println("version="+xl.getProperty("Version"));
System.out.println("version="+Dispatch.get(xlo, "Version"));
xl.setProperty("Visible", new Variant(true));
Object workbooks = xl.getProperty("Workbooks").toDispatch();
Object workbook = Dispatch.get(workbooks,"Add").toDispatch();
Object sheet = Dispatch.get(workbook,"ActiveSheet").toDispatch();
Object a1 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
new Object[] {"A1"},
new int[1]).toDispatch();
Object 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[] {});
}
}
}
No comments:
Post a Comment