简体   繁体   English

Poi API XSSFWorkbook工作表演员表EXCEPTION

[英]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 线程“主”中的异常java.lang.ClassCastException:org.apache.poi.xssf.usermodel.XSSFSheet无法转换为org.apache.poi.sl.usermodel.Sheet

You imported the wrong version of Sheet . 您导入了错误版本的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. 代表Excel工作表,您的代码应该可以正常工作。 No cast should be needed for Sheet , Row and Cell . SheetRowCell不需要Cell


If you look at the XSSFSheet class definition, you can see that it implements org.apache.poi.ss.usermodel.Sheet . 如果查看XSSFSheet类定义,则可以看到它实现了org.apache.poi.ss.usermodel.Sheet On the other hand, the org.apache.poi.sl.usermodel.Sheet interface is related with PowerPoint ; 另一方面, org.apache.poi.sl.usermodel.Sheet接口与PowerPoint相关; in fact, according to the Javadoc, it's the 实际上,根据Javadoc,

Common parent interface for Slides , Notes and Masters 常见父接口SlidesNotesMasters

So .ss. 所以.ss. = Excel (XSSF), and .sl. = Excel (XSSF)和.sl. = PowerPoint (XSLF). = PowerPoint (XSLF)。 The fact that these two interfaces have the same name may actually be misleading. 这两个接口名称相同的事实实际上可能会产生误导。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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