简体   繁体   中英

Force close an excel file before writing to it

I am writing to an existing excel file using Java, say this is fileA. (I'm using APACHE POI for this.) It is possible that the excel fileA is opened by someone. It is saved in a shared folder accessed by a lot of people.

I want to avoid encountering

java.io.FileNotFoundException: (The process cannot access the file because it is being used by another process)

Because no matter if the existing excel file is opened or not, I need to save the output of my Java app.

Upon researching, I think it is impossible to close fileA (opened by some other process/user, not by my Java App) within my Java code.

What I'm doing now is to create a new excel file, say fileB if fileA is currently opened. I'm using the code below. File file = null;

    FileOutputStream out = null;

    int workbookNo = 0;
    do{
        String append = "";
        if(workbookNo != 0){
            append = "_Copy" + Integer.toString(workbookNo);
        }
        file = new File(filePath + "ValidateLock_" + dataDate + append + ".xlsx");

        try{
            out = new FileOutputStream(file);
            workbookNo = 0;
        }catch(FileNotFoundException e){
            //e.printStackTrace();
            workbookNo++; 
        }
    }while(workbookNo != 0);

However, I'm getting the error below.

org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file

try like this :

    try {
                FileInputStream file = new FileInputStream(new File("C:\\update.xls"));

                HSSFWorkbook workbook = new HSSFWorkbook(file);
                HSSFSheet sheet = workbook.getSheetAt(0);
                Cell cell = null;

                //Update the value of cell
                cell = sheet.getRow(1).getCell(2);
                cell.setCellValue(cell.getNumericCellValue() * 2);
                cell = sheet.getRow(2).getCell(2);
                cell.setCellValue(cell.getNumericCellValue() * 2);
                cell = sheet.getRow(3).getCell(2);
                cell.setCellValue(cell.getNumericCellValue() * 2);
    //Close the excel input file (inputstream)
                file.close();

                FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
                workbook.write(outFile);
//Close output excel file
                outFile.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

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