我在这方面尝试了很多答案,但仍然无法解决。 我的java文件如下:
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;
}
}
我的模型如下:
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
}
此问题是因为 extCode 的 header 是字符串,而该列中的值是整数。即使我跳过标题并阅读其余部分,也会出现错误。当我将 extCode 的数据类型更改为字符串时,错误会反转并显示“无法从数字单元格获取字符串单元格”。请有人帮助我消除这个错误
最佳答案
当您从单元格中获取值(value)时进行检查。它应该像下面这样。
case 2:
if(cell. getCellType() == CellType.NUMERIC){
employee.setExtCode((int) cell.getNumericCellValue());
}else{
employee.setExtCode(Integer.valueOf(cell.getStringCellValue()));
}
break;
有多种受支持的单元格类型 POI API。欲了解更多信息,请访问link
编辑:
如果上述解决方案不起作用,您可以简单地执行
cell.setCellType(Cell.CELL_TYPE_STRING);
employee.setExtCode(Integer.valueOf(cell.getStringCellValue()));
在从单元格读取值之前。然而,POI documentation明确表示使用 setCellType 从单元格中读取值,因为您可能会丢失单元格的原始格式。您可以使用 DataFormatter 而不是使用它。 。代码应该如下所示(我没有编译并运行)。
String strValue = new DataFormatter().formatCellValue(cell);
关于java - 无法从 STRING 单元格错误中获取 NUMERIC 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48576526/