我想读取Excel单元格的内容并将其插入数组列表中,但是出现以下错误:类型不兼容,单元格无法转换为String 怎么解决这个问题?!
存在错误的部分代码:
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// Now let's iterate over the columns of the current row
Iterator<Cell> cellIterator = row.cellIterator();
int j=0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
Double cellValue;
cellValue = Double.parseDouble(cell);
dataPoint.add(cellValue);
System.out.print(cellValue + "\t");
}
答案 0 :(得分:0)
Double#parseDouble
带有一个String
参数,但是您试图将Cell
对象传递给它。
您可以使用cell.getStringCellValue();
获取单元格值。因此,您的代码应如下所示:
cellValue = Double.parseDouble(cell.getStringCellValue());
如果您遇到从numeric cell
获取单元格值作为String的任何问题,可以在从单元格获取值之前调用String
将单元格类型设置为cell.setCellType(Cell.CELL_TYPE_STRING)
。
cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = Double.parseDouble(cell.getStringCellValue());
编辑:
但是,建议我们应该检查单元格类型,然后相应地获取单元格的值,而不是设置单元格类型Cell#setCellType
来获取值。有关更多信息,请访问link。
答案 1 :(得分:0)
我尝试首先检查单元格类型的新代码!
for (Row row : sheet1) {
for (Cell cell : row) {
// Alternatively, get the value and format it yourself
switch (cell.getCellType()) {
case CellType.NUMERIC:
cellValue=cell.getNumericCellValue();
break;
default:
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
System.out.println("The cell"+cellRef.formatAsString()+"Does not contain numeric value");
}
dataPoint.add(cellValue);
}
}