简体   繁体   中英

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;
                }
            }
        }
    }
}

I get an exception after running the above code:

Exception in thread "main" java.lang.ClassCastException: org.apache.poi.xssf.usermodel.XSSFSheet cannot be cast to org.apache.poi.sl.usermodel.Sheet

You imported the wrong version of Sheet . Simply turn

import org.apache.poi.sl.usermodel.Sheet;

into

import org.apache.poi.ss.usermodel.Sheet;

that represents the Excel worksheet, and your code should work. No cast should be needed for Sheet , Row and Cell .


If you look at the XSSFSheet class definition, you can see that it implements org.apache.poi.ss.usermodel.Sheet . On the other hand, the org.apache.poi.sl.usermodel.Sheet interface is related with PowerPoint ; in fact, according to the Javadoc, it's the

Common parent interface for Slides , Notes and Masters

So .ss. = Excel (XSSF), and .sl. = PowerPoint (XSLF). The fact that these two interfaces have the same name may actually be misleading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM