private static List<ImportViewModel> readExcelFile() { List<ImportViewModel> datas = new ArrayList<>(); FileInputStream inputStream = null; Workbook workbook = null; try { inputStream = new FileInputStream("/sdcard/Template/IC1001.xlsx"); workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.rowIterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); ImportViewModel importViewModel = new ImportViewModel(); Iterator<Cell> columnIterator = row.cellIterator(); while (columnIterator.hasNext()) { Cell cell= columnIterator.next(); importViewModel.setName("商品名称:" + columnIterator.next().getStringCellValue()); importViewModel.setType("商品类型:" + columnIterator.next().getStringCellValue()); importViewModel.setStyle("商品款式:" + columnIterator.next().getStringCellValue()); importViewModel.setInventoryNum("预期应有库存:" + columnIterator.next().getStringCellValue()); datas.add(importViewModel); } } } catch (IOException | InvalidFormatException e) { e.printStackTrace(); } finally { try { if (workbook != null) { workbook.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return datas; }java.util.NoSuchElementException怎么修改
时间: 2023-11-28 22:48:50 浏览: 53
jsp页面iterator遍历数组、Map、List
java.util.NoSuchElementException异常通常发生在当你试图访问一个没有下一个元素的迭代器时。在你的代码中,这可能是因为你每次迭代器循环时都调用了两次`columnIterator.next()`方法,而在某些情况下,这会导致迭代器尝试读取不存在的下一个元素。要修复这个问题,你可以将两个方法调用合并为一个方法调用,如下所示:
```
while (columnIterator.hasNext()) {
Cell cell = columnIterator.next();
importViewModel.setName("商品名称:" + cell.getStringCellValue());
importViewModel.setType("商品类型:" + cell.getStringCellValue());
importViewModel.setStyle("商品款式:" + cell.getStringCellValue());
importViewModel.setInventoryNum("预期应有库存:" + cell.getStringCellValue());
datas.add(importViewModel);
}
```
这样,每次迭代时只会调用一次`columnIterator.next()`方法,从而避免了可能导致`NoSuchElementException`异常的问题。
阅读全文