调试过的代码,供有相同需求的学习使用。相当于可以把Exce与CAD相接合使用的第一步工作。
一、调用CAD
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class testCAD {
public static void main(String[] args) {
// 此程序会创建一个新的AutoCAD实例,创建过程中的蓝色字体为对象中的实际名称
// 只能按VBA中的名称使用,否则错误。其它变量名可不采用VBA名称
ComThread.InitSTA();// 开启线程
ActiveXComponent CADApp = new ActiveXComponent("AutoCAD.Application"); // 调用CAD
CADApp.setProperty("Visible", new Variant(true)); // 使CAD可见,隐藏为fase
Dispatch ActDoc = CADApp.getObject(); // 在CAD创建一个Application对象
Dispatch activeDocument = Dispatch.call(ActDoc, "ActiveDocument").getDispatch(); // 在Appliction创建一个ActiveDoucument对象
Dispatch modelSpace = Dispatch.call(activeDocument, "ModelSpace").getDispatch();// 在ActiveDoucument创建ModelSpace
double[] centerPoint = { 100.0, 200.0, 0.0 }; // 用双精度数组形式定义点坐标{X,Y,Z}
double radius = 300.0; // 定义园半径
Dispatch circleObj = Dispatch.call(modelSpace, "AddCircle", centerPoint, radius).getDispatch(); // 在ModelSpace画园
double[] endPoint = { 600, 300, 0 };
Dispatch.call(modelSpace, "AddLine", centerPoint, endPoint);
String acRed = "acRed";
Dispatch.call(circleObj, "Color", acRed);
// 加载线型
String cadLinObj = "acad.lin";
Dispatch lineTypes = Dispatch.call(ActDoc, "Load", cadLinObj).getDispatch();
ComThread.Release();// 结束线程
}
}
二、调用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();
}
}
}