2015-04-20 48 views
0
int sheets = 0; 
    try { 
     Workbook book = WorkbookFactory.create(file); 
     sheets = book.getNumberOfSheets(); 
     book.close(); //Exception occurs in this line 
    } catch (Exception e) { 
     logger.warn(e.getMessage()); 
     throw new Exception("exception in readding number of sheets", e.getCause()); 
    } 
    return sheets; 

在XLSX文件表的我得到這個異常:地理位置異常查找no。使用Apache POI

org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save: an error occurs while saving the package : part. 

有任何解決方法,以這種例外?

+0

在關閉工作簿之前,您必須將工作簿保存到某些內容中。查看此鏈接http://poi.apache.org/spreadsheet/quick-guide.html#NewWorkbook – Justin

+0

這就是我只想要的數字的牀單。沒有別的。它適用於xls文件,但在xlsx文件的情況下出現此錯誤。 – user1615664

+1

嘗試使用只讀模式。 Files.newInputStream(path,StandardOpenOption.READ) – Justin

回答

1

這是我在poi 3.11版本上測試的結果,正如你在評論中所說的那樣。

你的代碼對我來說工作得很好!

import java.io.File; 
import java.io.FileInputStream; 
import java.io.InputStream; 

import org.apache.poi.ss.usermodel.Workbook; 
import org.apache.poi.ss.usermodel.WorkbookFactory; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

public class POITest { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     File file = new File("F:\\test.xlsx"); 

     int sheets = 0; 
     try { 
      Workbook book = WorkbookFactory.create(file); 
      sheets = book.getNumberOfSheets(); 
      System.out.println(sheets); 
      book.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     try { 
      InputStream file2 = new FileInputStream("F:\\test.xlsx"); 
      Workbook book = new XSSFWorkbook(file2); 
      sheets = book.getNumberOfSheets(); 
      System.out.println(sheets); 
      book.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

} 

對於上面的代碼,它可以毫無例外地運行並打印出數量的紙張。我還提供了另一種方式來新建Workbook。如果你仍然遇到異常,也許你可以嘗試另一個'純'的Excel文件(新的Excel文件,並直接保存而不插入任何數據)並再次測試。