[英]POI cannot open workbook to open .xls files and eclipse throw an exception
When I try to open a .xlsx file in POI, I get an exception: 当我尝试在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();
just trying to read the data that .xls file contain but cannot open it ! 仅尝试读取.xls文件包含的数据,但无法打开它!
Don't create an HSSFWorkbook
on a .xlsx
file. 不要在
.xlsx
文件上创建HSSFWorkbook
。 An HSSFWorkbook
represents an .xls
file, and an XSSFWorkbook
represents an .xlsx
file. HSSFWorkbook
代表.xls
文件,而XSSFWorkbook
代表.xlsx
文件。
In fact, usually your code doesn't even need to know which it's working with. 实际上,通常您的代码甚至不需要知道它在使用哪个代码。 Create your
Workbook
with WorkbookFactory
, as this example from the Busy Developer's Guide shows: 使用
WorkbookFactory
创建Workbook
WorkbookFactory
,如《忙碌的开发人员指南》中的以下示例所示:
// 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"));
If you must, you can create an XSSFWorkbook
directly: 如果需要,可以直接创建
XSSFWorkbook
:
XSSFWorkbook wb = new XSSFWorkbook(inputStream); // You can use a FileInputStream
or with an OPCPackage
. 或使用
OPCPackage
。
OPCPackage pkg = OPCPackage.open(myInputStream);
XSSFWorkbook wb = new XSSFWorkbook(pkg);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.