不兼容的类型:单元格到String任何想法如何解决问题?

时间:2019-03-02 17:16:09

标签: java apache apache-poi

我想读取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");
    }

2 个答案:

答案 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);
        }
    }