String excelApplicationProgramId = "Excel.Application";
String excelSheetProgramId = "Excel.Sheet";
String typeLibLocation = "C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE";
// Grab The Component.
ActiveXComponent axc = new ActiveXComponent(excelApplicationProgramId);
hookupListener(axc, excelApplicationProgramId, typeLibLocation);
try {
System.out.println("version=" + axc.getProperty("Version"));
System.out.println("version=" + Dispatch.get(axc, "Version"));
axc.setProperty("Visible", true);
Dispatch workbooks = axc.getPropertyAsComponent("Workbooks");
Dispatch workbook = Dispatch.get(workbooks, "Add").toDispatch();
Dispatch sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
hookupListener(sheet, excelSheetProgramId, typeLibLocation);
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();
System.out.println("Inserting value into A1");
System.out.println("Inserting calculation 2xA1 into A2");
Dispatch.put(a1, "Value", "123.456");
Dispatch.put(a2, "Formula", "=A1*2");
System.out.println("Retrieved a1 from excel:"
+ Dispatch.get(a1, "Value"));
System.out.println("Retrieved a2 from excel:"
+ Dispatch.get(a2, "Value"));
Variant f = new Variant(false);
Dispatch.call(workbook, "Close", f);
axc.invoke("Quit", new Variant[] {});
} catch (ComException cfe) {
cfe.printStackTrace();
fail("Failed to attach to " + excelApplicationProgramId + ": "
+ cfe.getMessage());