I have tried many SO answers on this regard but still I could not resolve. My java file is as follows:
public class ReadExcelFileAndStore {
public List getTheFileAsObject(String filePath){
List <Employee> employeeList = new ArrayList<>();
try {
FileInputStream file = new FileInputStream(new File(filePath));
// Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook(file);
int numberOfSheets = workbook.getNumberOfSheets();
//System.out.println(numberOfSheets);
//loop through each of the sheets
for(int i = 0; i < numberOfSheets; i++) {
String sheetName = workbook.getSheetName(i);
System.out.println(sheetName);
// Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(i);
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
// Get Each Row
Row row = rowIterator.next();
//Leaving the first row alone as it is header
if (row.getRowNum() == 0) {
continue;
}
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
Employee employee = new Employee();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int columnIndex = cell.getColumnIndex();
switch (columnIndex + 1) {
case 1:
employee.setEmpName(cell.getStringCellValue());
break;
case 2:
employee.setExtCode((int) cell.getNumericCellValue());
break;
case 3:
employee.setDepartment(cell.getStringCellValue());
break;
}
}
employeeList.add(employee);
}
}
file.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return employeeList;
}
}
I have the model as follows:
package com.restfapi.demo.Model;
public class Employee {
private String empName;
private int extCode;
private String department;
public Employee(){
}
public Employee(String empName,int extCode, String department){
this.empName = empName;
this.extCode = extCode;
this.department = department;
}
//all getters and setters are followed
}
This problem is because the header of extCode is string and the values in that column are integers. Even if I skip the header and read the rest, the error appears.When I changed the datatype of extCode to String the error is reversed and getting "Cannot get a STRING cell from a NUMERIC cell". Please somebody help me to get rid of this error