【发布时间】:2015-02-24 03:25:05
【问题描述】:
我有优秀的。我为 excel 文件创建宏以从其他资源中读取数据。该宏每秒运行一次并更新其 Excel 单元格。
现在,我想构建一个java程序来每秒读取excel数据。我已经尝试过 Apache POI,但是在我检查了documentation ti 后,ti 不支持使用宏读取 excel 文件。
我从一些资源中读取 Java Com Bridge (JCOB) 可用于读取带有宏的 excel。我试过了,但是每次我尝试我的代码时单元格值仍然没有更新。
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)
{
}
}
【问题讨论】: