我试图在电子表格中迭代一组信息,我的电子表格有三列和两行。
这是我用来迭代信息的代码,
private List<DataRecord> allData = new ArrayList<>();
public DataRepository(String excelFilePath) {
FileInputStream inputStream;
try {
inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
DataRecord record = new DataRecord();
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
record.setCardNumber(cellIterator.next().getStringCellValue());
record.setCvv(cellIterator.next().getStringCellValue());
record.setPostcode(cellIterator.next().getStringCellValue());
}
allData.add(record);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public List<DataRecord> getAllData() {
return allData;
}
public void setAllData(List<DataRecord> allData) {
this.allData = allData;
}
这在今天早上起作用,现在它似乎抛出了上述异常,我不确定为什么。
由于
这是完整的堆栈跟踪
Caused by: java.util.NoSuchElementException: null
at java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1205)
at java.util.TreeMap$ValueIterator.next(TreeMap.java:1252)
at gov.uk.dwp.epayments.repository.DataRepository.<init>(DataRepository.java:43)
at gov.uk.dwp.epayments.service.PayService.<init>(PayService.java:11)
at gov.uk.dwp.epayments.controller.PaymentController.<init>(PaymentController.java:23)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
... 18 common frames omitted
答案 0 :(得分:1)
这段代码做得不好,导致之前调用next(),以确定是否有下一个单元格
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
record.setCardNumber(cellIterator.next().getStringCellValue());
record.setCvv(cellIterator.next().getStringCellValue());
record.setPostcode(cellIterator.next().getStringCellValue());
}
如果它有下一个项目但是前进三次,您将检查一次。 (下三个例子)
如果你每行只有树单元格,你可以用这种方式(它是许多可能的解决方案中唯一的一个):
Iterator<Cell> cellIterator = nextRow.cellIterator();
if(cellIterator.hasNext(){
record.setCardNumber(cellIterator.next().getStringCellValue());
}
if(cellIterator.hasNext(){
record.setCvv(cellIterator.next().getStringCellValue());
}
if(cellIterator.hasNext(){
record.setPostcode(cellIterator.next().getStringCellValue());
}