Excel 如果 Excel- 文件打开,则 Java- 程序无法访问文件

Excel File can't be accessed by Java-Program if Excel-file is open

我的代码应该将一个数字(在本例中为数字 5)打印到指定 Excel 工作簿中的指定单元格。如果 Excel-Workbook 关闭,则代码有效。但是,如果 Excel-Workbook 打开,我在 运行 代码时收到以下错误消息:

Exception in thread "main" java.io.FileNotFoundException: C:\Users\Username\Desktop\java-Programs\test.xlsm (The process can't access the   file because it is used by another process)

代码如下:

XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File("C:\Users\Username\Desktop\java-Programs\test.xlsm")));
XSSFSheet ExcelSheet = wb.getSheet("Output");
XSSFRow row = ExcelSheet.getRow(3);
XSSFCell cell = row.getCell(0);

cell.setCellValue(5);

FileOutputStream fileOut = new FileOutputStream("C:\Users\Username\Desktop\java-Programs\test.xlsm");
wb.write(fileOut);
fileOut.close();

我想在 运行 java 代码时保持文件打开。有谁知道我必须更改什么才能在 运行 代码时保持 Excel-文件打开?

Microsoft Excel 对其打开的文件设置排他锁。

因此,如果您在 Excel 中打开文件时尝试在任何其他应用程序中写入文件,它将在 Windows 时失败。

当您需要写入文件时,可能没有其他解决方案可以关闭 Excel。