我正在尝试使用以下代码从excel文件中读取:
File file = new File("/C:/behzad-data/trp.small.xlsx");
String dataPath=file.getAbsolutePath();
System.out.println(dataPath);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
//XSSFWorkbook wb = new XSSFWorkbook(file);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
但它抱怨:
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:152)
所以我看到this,并使其像
XSSFWorkbook wb = new XSSFWorkbook(file);
// HSSFWorkbook wb = new HSSFWorkbook(fs);
但它抱怨:
Type mismatch: cannot convert from XSSFSheet to HSSFSheet
如何同时解决这两个错误?
答案 0 :(得分:0)
为什么不使用WorkbookFactory
并且只需处理两种类型工作簿的API?因此,使用这个新API,您不必使用文件类型优先Sheet
,Row
等,只需使用这些类。
File file = new File("C:\\behzad-data\\trp.small.xlsx");
Workbook wb = WorkbookFactory.create(file);
Sheet sheet = wb.getSheetAt(0);
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
Row row = rows.next();
// so on and so forth
}
然后正常使用wb
查看API文档以获取更多信息HERE
注意:这需要这些依赖关系
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16-beta2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16-beta2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.16-beta2</version>
</dependency>