【发布时间】:2017-11-23 14:57:21
【问题描述】:
我有一个包含宏的 Excel 文件,我想自动化该过程。我有填充 Excel 列的 Java 代码,并且我已经编写了 VBScript 来在 Excel 中运行宏。
我的 Java 代码是(我传递了具有宏的 Excel 文件名)
public void excelupdate(String fileName) {
FileInputStream file = null;
FileOutputStream out = null;
try {
file = new FileInputStream(new File(fileName));
HSSFWorkbook yourworkbook = new HSSFWorkbook(file);
HSSFSheet sheet1 = null;
for (int i = 0; i < yourworkbook.getNumberOfSheets(); i++) {
if (yourworkbook.getSheetName(i).contains("Sheet-Macro")) {
sheet1 = yourworkbook.getSheetAt(i);
}
}
Cell cell = null;
int rowValue = 10;
for (int i = 0; i < list.size() - 1; i++) {
cell = sheet1.getRow(rowValue).getCell(2);
cell.setCellValue(list.get(i));
rowValue++;
}
Cell cell1 = null;
int rowValue1 = 10;
for (int j = 0; j < Input1list.size() - 1; j++) {
cell1 = sheet1.getRow(rowValue1).getCell(3);
cell1.setCellValue(Input1list.get(j));
rowValue1++;
}
Cell cell2 = null;
int rowValue2 = 22;
for (int k = 0; k < Input2list.size() - 1; k++) {
cell2 = sheet1.getRow(rowValue2).getCell(4);
cell2.setCellValue(Input2list.get(k));
rowValue2++;
}
out = new FileOutputStream(("C:\\Users\\Desktop\\EXCEL.xls"));
yourworkbook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (Exception e) {
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
}
}
Java 代码在 Apache Poi 上运行以填充列并将 Excel 文件移动到特定目录,然后我有以下 VBScript 来运行宏:
Dim objXL
Set objXL = CreateObject("Excel.Application")
Set objWorkbook = objXL.Workbooks.Open("F:\testmacro\testmacro\EXCEL.xls")
objWorkbook.Sheets("AD stages").Cells(6, 4) = "F:\set1\set.txt"
objXL.Application.DisplayAlerts = False
objXL.ActiveWorkbook.Save
objXL.Application.Run "macro_cal"
objXL.ActiveWorkbook.Save
objXL.ActiveWorkbook.Close
objXL.Application.DisplayAlerts = True
objXL.Application.Quit
WScript.Echo "ExCEL file updated successfully"
WScript.Quit
Set objXL = Nothing
我从java中调用上面的VBscript如下,
File file = new File(excelFilename);
file.setExecutable(true);
file.setReadable(true);
file.setWritable(true);
Runtime runtime = Runtime.getRuntime();
try {
String sample="cmd /c start "+vbScript+" "+"\"" +excelFilename + "\"" + " "+"\"" +outFile + "\"";
System.out.println(sample);
Process process1 = runtime.exec(sample);
} catch (IOException e) {
logger.error(e);
}
但问题是,一旦 Java 填充 Excel 列并保存文件,文件就会受到保护,因此 VBScript 会抛出错误,说明它无法在受保护的 Excel 中打开/运行宏。
有什么建议吗?
【问题讨论】:
-
您在问为什么 Java 代码保持打开文件,但您没有共享该 Java 代码。
-
"一旦 java 填充了 excel 列并保存文件,文件就会受到保护":绝对不是。也许它被锁定但不受保护。 VBScript 究竟抛出了什么错误?
-
确保
out.close();行被执行。 -
请阅读Error message in Microsoft Office: "Office has detected a problem with this file"。因此,似乎位置
F:\testmacro\testmacro不是其中包含宏的 Excel 文件的受信任位置。但是在C:\Users\Desktop\EXCEL.xls上创建的文件是如何到达F:\testmacro\testmacro的呢? -
@AxelRichter 非常感谢。我不知道添加受信任的位置。请提及它作为答案,我可以标记它。
标签: java excel vbscript apache-poi vba