POI无法打开工作簿以打开.xls文件,eclipse会抛出异常

时间:2014-01-16 16:38:57

标签: java database eclipse excel apache-poi

当我尝试在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文件包含但无法打开它的数据!

1 个答案:

答案 0 :(得分:5)

不要在HSSFWorkbook文件上创建.xlsxHSSFWorkbook代表.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);