2008-04-15
java调用Excel中Replace的实现方法(jacob)
ActiveXComponent activeXApp = null;
File file = new File(localFilePath);
try {
activeXApp = new ActiveXComponent("Excel.Application");
activeXApp.setProperty("Visible", new Variant(false));
activeXApp.setProperty("DisplayAlerts", new Variant(false));
Dispatch workbooks = activeXApp.getProperty("Workbooks")
.toDispatch();
Dispatch sheet = null;
Dispatch sheets = null;
Dispatch usedRange = null;
Dispatch workbook = Dispatch.invoke(
workbooks,
"Open",
Dispatch.Method,
new Object[] { file.getAbsolutePath(),
new Variant(false), new Variant(false) },
new int[1]).toDispatch();
Variant xlLookAt = new Variant(new Integer(2));
Variant xlSearchOrder = new Variant(new Integer(1));
Variant matchCase = new Variant(true);
sheets = Dispatch.get(workbook, "Sheets").toDispatch();
int count = Dispatch.get(sheets, "Count").getInt();
for (int j = 1; j <= count; j++) {
sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get,
new Object[] { new Integer(j) }, new int[1])
.toDispatch();
usedRange = Dispatch.get(sheet, "UsedRange").toDispatch();
Dispatch.invoke(usedRange, "Replace", Dispatch.Method,
new Object[] { "originalCharacterString", "replaceCharacterString", xlLookAt, xlSearchOrder,
matchCase }, new int[1]);
}
Dispatch.call(workbook, "Save");
Dispatch.call(workbook, "Close", new Variant(false));
} catch (Exception e) {
throw e;
} finally {
if (activeXApp != null) {
activeXApp.invoke("Quit", new Variant[] {});
}
ComThread.Release();
}







评论排行榜