在写入之前强制关闭excel文件

时间:2016-10-05 03:51:24

标签: java excel apache-poi

我正在使用Java写一个现有的excel文件,比如说这是fileA。 (我为此使用了APACHE POI。) excel fileA可能是由某人打开的。它保存在很多人访问的共享文件夹中。

我想避免遇到

  

java.io.FileNotFoundException :(进程无法访问该文件   因为它正被另一个进程使用)

因为无论是否打开现有的excel文件,我都需要保存Java应用程序的输出。

经过研究,我认为在我的Java代码中关闭fileA(由其他进程/用户打开,而不是由我的Java App打开)是不可能的。

我现在正在做的是创建一个新的excel文件,比如fileB,如果fileA当前打开的话。我使用下面的代码。         文件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);

但是,我收到以下错误。

  

org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException:否   找到有效的条目或内容,这不是有效的OOXML(Office   打开XML)文件

1 个答案:

答案 0 :(得分:0)

尝试这样:

    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();
            }