使用pache poi 4.1.0给出多个错误

时间:2019-04-21 16:22:54

标签: java excel apache-poi

我正在创建读取excel文件的代码,并且我正在使用Apache poi 4.1.0依赖性读取文件,但是它给了我很多错误:

以下是我的依赖项:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.0</version>
</dependency>

以下是我的代码:

public class Excel {
    private static final String path = "C:\\Users\\Desktop\\Excel.xlsx";        
    public static void main(String[] args) throws IOException {         
        List studentList = getStudentListFromExcel();
    }       
    private static List getStudentListFromExcel() throws IOException{
        List studentList = new ArrayList();
        FileInputStream fis = null;         
        try {
            fis = new FileInputStream(path);
            // Using XSSF for xlsx format
            Workbook wb = new XSSFWorkbook(fis);
            int noSheet = wb.getNumberOfSheets();               
            for(int i=0;i<noSheet; i++) {
                Sheet sh = wb.getSheetAt(i);
                Iterator rowIterator = sh.iterator();
            while(rowIterator.hasNext()) {                  
                Student student = new Student();
                Row row = (Row) rowIterator.next();
                Iterator cellIterator = row.cellIterator();                 
                while(cellIterator.hasNext()) {
                    Cell cell = (Cell) cellIterator.next();
                    if(Cell.CELL_TYPE_STRING == cell.getCellType()) { // Error <===== CELL_TYPE_STRING cannot be resolved or is not a field    
                        student.setName(cell.getStringCellValue());   // Error <===== The method setName(String) is undefined for the type Student
                    }
                }
            }               
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
        return studentList;         
    }   
}

2 个答案:

答案 0 :(得分:0)

尝试使用此枚举: https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/CellType.html

而不是您现在正在使用的那个。

答案 1 :(得分:0)

尝试一下,

1。错误一-CELL_TYPE_STRING cannot be resolved or is not a field

if(CellType.STRING == cell.getCellTypeEnum()){
    student.setName(cell.getStringCellValue());
}

2。错误二-The method setName(String) is undefined for the type Student

确保您导入的包正确并重新编译Student类