Java 不兼容类型:单元格字符串有没有解决问题的方法?

Java 不兼容类型:单元格字符串有没有解决问题的方法?,java,apache,apache-poi,Java,Apache,Apache Poi,我想读取Excel单元格的内容并将其插入数组列表中,但出现以下错误:类型不兼容,单元格无法转换为字符串 如何解决问题plz 存在错误的代码的一部分: while (rowIterator.hasNext()) { Row row = rowIterator.next(); // Now let's iterate over the columns of the current row Iterator<Cell> cellIterator = row.cel

我想读取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");
    }
while(roweiterator.hasNext()){
行=行迭代器。下一步();
//现在让我们遍历当前行的列
迭代器cellIterator=row.cellIterator();
int j=0;
while(cellIterator.hasNext()){
Cell=cellIterator.next();
双细胞值;
cellValue=Double.parseDouble(单元格);
dataPoint.add(cellValue);
系统输出打印(cellValue+“\t”);
}
Double#parseDouble
接受一个
字符串
参数,但您试图将
单元格
对象传递给它

您可以使用
cell.getStringCellValue();
获取单元格值。因此,您的代码如下所示:

cellValue = Double.parseDouble(cell.getStringCellValue());
如果要从
数值单元格
中获取字符串形式的单元格值时遇到任何问题,可以在从单元格获取值之前,通过调用
cell.setCellType(cell.cell\u type\u String)
将单元格类型设置为
String

cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = Double.parseDouble(cell.getStringCellValue());
编辑:


但是,建议我们检查单元格类型,然后相应地获取单元格的值,而不是设置单元格类型
cell#setCellType
来获取值。有关更多信息,请访问。

我尝试首先检查单元格类型的新代码

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

我这样做了,我得到了这个错误:线程“main”中的异常java.lang.IllegalStateException:无法从数值单元格中获取字符串值。不建议将所有单元格类型更改为字符串。如果使用数学公式中引用的数值单元格执行此操作,则这些公式可能无法使用字符串单元格内容。请按建议执行。@AxelRichter是的,我同意您的意见。通常,我们应该检查单元格类型,然后相应地获取单元格内容。我以前尝试检查过内容,但行中出现错误:CellType.NUMERIC。错误类型不兼容:单元格类型无法按照中的建议转换为intDo。