当我尝试在POI中打开.xlsx文件时,我得到一个例外:
java.lang.IllegalArgumentException: The supplied POIFSFileSystem does not contain a BIFF8 'Workbook' entry. Is it really an excel file?
at org.apache.poi.hssf.usermodel.HSSFWorkbook.getWorkbookDirEntryName(HSSFWorkbook.java:223)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:245)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:188)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:170)
InputStream input = new BufferedInputStream( new FileInputStream(fileName));
POIFSFileSystem file = new POIFSFileSystem( input );
//Create Workbook instance holding reference to .xls file
HSSFWorkbook wb = new HSSFWorkbook(file);
//Get first/desired sheet from the workbook
HSSFSheet sheet = wb.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
只是试图读取.xls文件包含但无法打开它的数据!
答案 0 :(得分:5)
不要在HSSFWorkbook
文件上创建.xlsx
。 HSSFWorkbook
代表.xls
文件,XSSFWorkbook
代表.xlsx
文件。
事实上,通常你的代码甚至不需要知道它正在使用它。使用Workbook
创建WorkbookFactory
,例如the Busy Developer's Guide显示:
// Use a file
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
// Use an InputStream, needs more memory
Workbook wb = WorkbookFactory.create(new FileInputStream("MyExcel.xlsx"));
如果必须,您可以直接创建XSSFWorkbook
:
XSSFWorkbook wb = new XSSFWorkbook(inputStream); // You can use a FileInputStream
或OPCPackage
。
OPCPackage pkg = OPCPackage.open(myInputStream);
XSSFWorkbook wb = new XSSFWorkbook(pkg);