2016-10-05 67 views
0

我正在使用Java写入现有的excel文件,假设这是fileA。 (我正在为此使用APACHE POI。) 有人可能会打开excel文件A.它被保存在一个被许多人访问的共享文件夹中。在写入之前强制关闭excel文件

我想避免遇到

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

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

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

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

但是,我得到下面的错误。

org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException:没有 有效条目或内容发现,这不是一个有效的OOXML(办公室 打开XML)文件

+2

哪条线产生该异常? –

+0

您是否尝试使用Apache POI 3.15?它具有更好的错误信息,用于解决常见的用户错误或空文件全部都是 – Gagravarr

+0

您是否尝试将文件复制到其他用户无法访问的沙箱中(内存中有ByteArray流或本地磁盘上只有您的计算机或应用程序有权访问),然后在完成后将文件复制回网络驱动器? – IceArdor

回答

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