使用Java从宏读取Excel

时间:2011-01-15 09:15:30

标签: java excel-vba vba excel

我很出色。我为excel文件创建宏来从其他资源中读取数据。宏每秒运行并更新其excel单元格。

现在,我想构建java程序,每隔几秒钟读取一次excel数据。我已经尝试过Apache POI,但在检查后documentation ti不支持用宏读取excel文件。

我从一些资源中读取Java Com Bridge(JCOB)可以用来读取宏的宏。我试过了,但是每次尝试我的代码时,单元格值仍然没有更新。

import com.jacob.com.*;
import com.jacob.activeX.*;

public class ExcelTest {
 private static ActiveXComponent xl;
 private static Dispatch workbooks = null;
 private static Dispatch workbook = null;
 private static Dispatch sheet = null;
 private static String filename = null;
 private static boolean readonly = false;

 public static void main(String[] args) {
  String file = "D:\\tutorial\\ApachePoi\\ratesource.xls";
  OpenExcel(file, false); // do not show false to open Excel
  System.out.println(GetValue("B46"));
 }

 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) },// whether to open read-only
     new int[1]).toDispatch();
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 // Read value
 private static String GetValue(String position) {
  if (workbook == null) {
   System.out.println("workbook is null");
  }
  sheet = Dispatch.get(workbook, "ActiveSheet").toDispatch();
  Object cell = Dispatch.invoke(sheet, "Range", Dispatch.Get,
    new Object[]{position}, new int[1]).toDispatch();
  String value = Dispatch.get((Dispatch) cell, "Value").toString();

  return value;
 }
 //1.3638356164383563
 //1.3638356164383563




 private static void SetValue (String position, String type, String value)  
 {  

 }



}

2 个答案:

答案 0 :(得分:1)

我不熟悉能够做你所描述的Excel引擎。

您是否考虑过与Excel交谈并在运行电子表时询问其值?我相信你可以用ODBC做到这一点。

另一种方法可能是创建工作表的OpenOffice版本并与OpenOffice交谈。

答案 1 :(得分:0)

一个陷阱是poi不会将现有excel写入的值更改为另一个文件,您可以看到差异

workbook.getSheet().getRow(1).getCell(0).setValue("test");

并将此(已更改)工作簿写入另一个文件

public void writeFile(String fileName) {
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(fileName);
        getWorkbook().write(fos);
        fos.close();
    } catch (IOException e) {
        System.out.println("IOException occurs");
        e.printStackTrace();
    }
}