0

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 ?

justcurious
  • 839
  • 3
  • 12
  • 29
steady_progress
  • 3,311
  • 10
  • 31
  • 62
  • 1
    You wishes don't count here. I think you should close the file. The POI library expects it to be closed. Unless you rewrite it or choose another you're stuck. Besides, what about simultaneous updates? How should the Java program know about any changes made while the file is open? Bad idea. – duffymo Oct 29 '15 at 15:00
  • 2
    This is a Windows limitation, nothing to do with Java or Apache POI – Gagravarr Oct 29 '15 at 15:11
  • If you want to see updates to cells in Excel as your code executes, either go the VBA route or use a program that talks to Excel over Excel's COM port. – IceArdor Nov 06 '15 at 09:43

1 Answers1

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.

centic
  • 15,565
  • 9
  • 68
  • 125