2014-09-24 38 views
2

我的代碼不工作,它總是顯示上述異常。 但我總是可以看到正在生成的tmp文件。org.apache.poi.openxml4j.exceptions.InvalidOperationException:無法打開指定的文件

這裏是代碼,可以有人請建議的內容:

FileInputStream fis =null; 
     try{ 
     fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls")); 

     Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis); 
       int numOfSheets = wb.getNumberOfSheets(); 
System.out.println("bhargo num of sheets is " + numOfSheets); 
     for(int i=0; i<numOfSheets; i++){ 
      org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(i); 
      Iterator<Row> rowIterator = sheet.iterator(); 
      while (rowIterator.hasNext()) 
      { 
       Row row = rowIterator.next(); 
       Iterator<Cell> cellIterator = row.cellIterator(); 
       while (cellIterator.hasNext()) { 
        Cell cell = (Cell) cellIterator.next(); 
        if (cell.getCellType() == cell.CELL_TYPE_STRING) { 
         System.out.println("bhargo cell value is " + cell.getStringCellValue().trim()); 
        } 
       } 
      } 
      } 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    finally{ 
     System.out.println("bhargo, closing the stream"); 
    try { 
     fis.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    } 

回答

1

我能解決我的問題。 我在Linux上工作,所以它被保存在文件中的舊版本的Excel

2

有一些問題在這裏:

fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls")); 
    Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis); 

首先,as explained in the Apache POI documentation,不,如果你有使用的InputStream一份文件!它更慢,並使用更多的內存

其次,XSSF是與.xlsx文件一起使用的代碼,但您的文件是.xls之一,所以這將不起作用。

第三,Apache的POI有代碼,它會自動計算出你是什麼樣的文件,並創建相應的工作簿您

你的代碼,因此應改爲

Workbook wb = WorkbookFactory.create(new File("/home/amar/Desktop/new/abc.xls")); 

這將創建正確的工作簿,直接從文件

+0

是,這正是我所認識和使用WorkbookFactory代替。 – 2014-09-24 11:33:45

+0

感謝分享 – 2014-09-24 11:34:08

+0

是'wb = new XSSFWorkbook(spreadSheetFileName);'同樣好,其中'spreadSheetFileName'是一個'String'嗎? – mbmast 2016-05-21 22:37:36