1、 下载JACOB包:http://danadler.com/jacob/
2、 安装配置
解压jacobBin_17.zip
(1)jacob.dll所在目录放到PATH中
(2)jacob.jar放到CLASSPATH中
3、使用jacob进行Excel控制,下面是我写的一个测试程序代码
import com.jacob.com.*; import com.jacob.activeX.*;
class ExcelTest { private static ActiveXComponent xl; private static Object workbooks = null; private static Object workbook = null; private static Object sheet = null; private static String filename =null; private static boolean readonly = false; public static void main(String[] args) { String file = "f:\\java\\test.xls"; OpenExcel(file,false);//false为不显示打开Excel SetValue("A1","Value","2"); System.out.println(GetValue("A3")); CloseExcel(false); } //打开Excel文档 private static void OpenExcel(String file,boolean f) { try { filename = file; xl = new ActiveXComponent("Excel.Application"); xl.setProperty("Visible", new Variant(f)); workbooks = xl.getProperty("Workbooks").toDispatch(); workbook = Dispatch.invoke(workbooks, "Open", Dispatch.Method, new Object[]{filename, new Variant(false), new Variant(readonly)},//是否以只读方式打开 new int[1] ).toDispatch(); }catch(Exception e) {e.printStackTrace();} } //关闭Excel文档 private static void CloseExcel(boolean f) { try { Dispatch.call(workbook,"Save"); Dispatch.call(workbook, "Close", new Variant(f)); } catch (Exception e) { e.printStackTrace(); } finally { xl.invoke("Quit", new Variant[] {}); } } //写入值 private static void SetValue(String position,String type,String value) { sheet = Dispatch.get(workbook,"ActiveSheet").toDispatch(); Object cell = Dispatch.invoke(sheet, "Range", Dispatch.Get, new Object[] {position}, new int[1]).toDispatch(); Dispatch.put(cell, type, value); }
//读取值 private static String GetValue(String position) { Object cell = Dispatch.invoke(sheet,"Range",Dispatch.Get,new Object[] {position},new int[1]).toDispatch(); String value = Dispatch.get(cell,"Value").toString(); return value; } } 
|