不兼容的类型:cell to String任何想法如何解决问题?

问题描述 投票:-1回答:2

我想读取Excel单元格的内容并将其插入数组列表但我得到以下错误:不兼容的类型,列表无法转换为字符串如何解决问题PLZ?!!

存在错误的代码的一部分:

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");
    }
java apache apache-poi
2个回答
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


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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.