【问题标题】:cellIterator.hasNext() returns false even the cell has value即使单元格具有值,cellIterator.hasNext() 也会返回 false
【发布时间】:2021-11-30 20:27:11
【问题描述】:

我使用以下方法从 excel (csv) 表中读取数据:

InputStream inputStream = new BufferedInputStream(multipartFile.getInputStream());
XSSFWorkbook myWorkBook = new XSSFWorkbook(inputStream);
List<String> cellList = new ArrayList<>();
XSSFSheet mySheet = myWorkBook.getSheetAt(0);

Iterator<Row> rowIterator = mySheet.iterator();
rowIterator.next();

while (rowIterator.hasNext()) {
    Row row = rowIterator.next();
    cellList.clear();
    Iterator<Cell> cellIterator = row.cellIterator();

    while (cellIterator.hasNext()) { // this returns false even the cell has data 
        Cell cell = cellIterator.next();
        cellList.add(cell.getStringCellValue());
    }
}

我想让cellIterator.hasNext() 在第二行(名称)中为空单元格值返回true。那么,我该怎么做呢?

Create Date  Uuid                                  Name
2021-09-29   2e81a2b6-3226-4fe0-b8bd-39f42239686d  admin
2021-09-30   610e9040-840c-48c5-aa64-f193ed896133  

【问题讨论】:

  • 你在 while 循环之前有一个 rowIterator.next() ,你忽略了它的结果。也许您并没有像您认为的那样在线?或者您可能正在跳过标题?
  • 我检查了,我的代码如上所示。该代码有什么问题?你能张贴更正的吗?问候

标签: java excel csv file readfile


【解决方案1】:

您不能让 cellIterator.hasNext() 为空的“名称”单元格返回 true。

如果事先知道列数,可以使用循环和row.getCell(index)

        for (int i = 0; i < 3; i++) {
            Cell cell = row.getCell(i);
            cellList.add(cell == null ? "Empty":cell.toString());
        }

如果不这样做,则必须先扫描文件以计算列数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    相关资源
    最近更新 更多