0

I am developing a Java class which generates an xls file through Apache POI. I need to run this class several and open the generated file several times a day. If I run the program while the file is still open in Excel, the program does not raise errors, but the file is not updated (I close it and reopen it, and it is still the same). Strangely, I don't get any exception, like reported in this question.

Is there a way to force an update of the opened Excel file? Otherwise, is it possible to use system calls to kill the excel window (I am using Windows) before writing the file?

Community
  • 1
  • 1
dipanda
  • 760
  • 1
  • 11
  • 24

1 Answers1

3

No. Excel would need to be notified when a workbook on the filesystem was modified by a software library. Excel could achieve this either by monitoring the filesystem itself or asking the operating system to notify it of changes. Then Excel would need to know how to respond to this event. Excel does something like this for files on network shares being simultaneously accessed by multiple instances of Excel on different computers, but I have no idea how it accomplishes this. The answer is the same for any other library that modifies workbooks outside of Excel's control/knowledge and is not specific to POI.

Excel on Windows usually acquires an exclusive OS-level write lock on a spreadsheet, so Java will get an IOException Permission Denied exception if trying to write to a workbook that Excel has a death grip on.

LibreOffice on Linux creates lock files on the filesystem, which Java can ignore and write to the file anyways. LibreOffice has a File > Reload feature to reread in whatever is on disk, but is a manual process.

Additionally, POI is not very well suited to the task of writing to the same file location where the workbook was read, since your options are either: 1) Copy the file to a temporary location and read it in, then repeatedly write out to some destination 2) Buffer the input file in a FileInputStream then write out to the same location as it was read (this will consume more memory during the initial read, until you close the FileInputStream). 3) Write to a temporary file location and rename the files on disk.

You might be better off finding software that can communicate with Excel over a COM connection or ActiveX server, which would give you closer to real time updates in Excel because Excel would behave as a server and your application would be a lightweight client.

IceArdor
  • 1,961
  • 19
  • 20