Reputation: 3731
My code is supposed to print a number (in this case the number 5) to a specified cell in a specified Excel Workbook. The code works if the Excel-Workbook is closed. However, if the Excel-Workbook is open, I get the following error message when running the code:
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)
The code is the following:
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();
I want to keep the file open when running the java code. Does anybody know what I have to change in order to be able to keep the Excel-File open when running the code ?
Upvotes: 0
Views: 1156
Reputation: 15872
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.
Upvotes: 2