简体   繁体   中英

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

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM