简体   繁体   中英

In java how can I unlock a file or write to a file opened by excel

I am currently writing a program that outputs to a excel file. (the same open it reads) I have a feeling that the users will open the file in excel before modifying in my application. While I do realize I could save a new file that is not as neat.

I am looking for a way to unlock the file from Excel or force the write of the file, can you please help?

I need to end up with a way of the file to be open in Excel and still be able to write to the file from java.

Thank you!

Edit:

To answer the question why I would want to unlock the file, well the program I am working on does not have a excel viewer built in, only the ability to update based on standardized input.

So the users will still be viewing the file in excel. If they need to open this program first that would be alright also.

I guess another option is how to open the file with write access while Excel can still read it?

Currently when opening I am using Apache POI HSSF/XSSF, once my program opens the file, if i try to open it in excel i get the following error: "Excel cannot open the file because the file format is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

There is a good reason why the file is locked. Try to think of the problem from the excel programmer's prespective. If you write a program that locks a file you want exclusive access to it, because you must be sure that the file is not modified in the meanwhile.

So even if you can unlock it you might cause excel, or in general the other program to crash, because it might read the file in an inconsistent state.

I recommend you to look at the file if it is locked an if so inform the user that the file you want to update is opened in another program. The user should close this program before your program can continue.

set file writable to true before creating excel file, then set file to readonly once excel file is created like so:

try{
        File file = new File("\*path*\");
          file.setWritable(true);
            OutputStream out = new FileOutputStream(file.getPath());
            HSSFWorkbook wb=new HSSFWorkbook();
             //Create Excel File
            wb.write(out);
            out.close();
            file.setReadOnly();
}catch (FileNotFoundException e){
             e.printStackTrace();
               }

The file must be set to readonly in order for the java program to write to file while the file is open

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