![](/img/trans.png)
[英]No exception in JAVA program when it reads xlsx file with XSSFWorkbook class in POI
[英]Poi api XSSFWorkbook sheet cast EXCEPTION
package apsel5;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class A {
public static void main(String[] args) throws Exception{
FileInputStream f = new FileInputStream("D:\\LeadSuite.xlsx");
XSSFWorkbook wbks = new XSSFWorkbook(f);
Sheet s = (Sheet) wbks.getSheet("TestSteps");
Iterator itr = s.iterator();
while(itr.hasNext()){
Row rowitr = (Row)itr.next();
Iterator cellitr = rowitr.cellIterator();
while(cellitr.hasNext()){
Cell cell1= (Cell)cellitr.next();
switch(cell1.getCellType()){
case Cell.CELL_TYPE_STRING:
System.out.println(cell1.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell1.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell1.getBooleanCellValue());
break;
}
}
}
}
}
運行以上代碼后出現異常:
線程“主”中的異常java.lang.ClassCastException:org.apache.poi.xssf.usermodel.XSSFSheet無法轉換為org.apache.poi.sl.usermodel.Sheet
您導入了錯誤版本的Sheet
。 只需打開
import org.apache.poi.sl.usermodel.Sheet;
成
import org.apache.poi.ss.usermodel.Sheet;
代表Excel工作表,您的代碼應該可以正常工作。 Sheet
, Row
和Cell
不需要Cell
。
如果查看XSSFSheet
類定義,則可以看到它實現了org.apache.poi.ss.usermodel.Sheet
。 另一方面, org.apache.poi.sl.usermodel.Sheet
接口與PowerPoint相關; 實際上,根據Javadoc,
常見父接口
Slides
,Notes
和Masters
所以.ss.
= Excel (XSSF)和.sl.
= PowerPoint (XSLF)。 這兩個接口名稱相同的事實實際上可能會產生誤導。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.