我的代码应该将一个数字(在本例中为数字5)打印到指定的Excel工作簿中的指定单元格。如果关闭Excel工作簿,代码将起作用。但是,如果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文件打开吗?
答案 0 :(得分:2)
Microsoft Excel puts an exclusive lock on files that it has open.
So if you try to write to the file in any other application while the file is open in Excel, it will fail on Windows.
There is likely no other solution then to close Excel when you need to write to the file.