更新迭代器循环内的列表



此代码试图迭代excel文件并将数据加载到List<List<String>>,但它将java.lang.NullPointerException抛出到resultList.add(rrow),但不清楚它的问题是什么:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ReadExcel {
public List<List<String>> resultList;

public List<List<String>> ReadExcelToList(String csvPath) throws IOException {
try {

FileInputStream excelFile = new FileInputStream(csvPath);
Workbook workbook = new XSSFWorkbook(excelFile);
System.out.println(workbook.getSheetName(0));
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {

Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
List<String> rrow = new ArrayList<>();
while (cellIterator.hasNext()) {

Cell currentCell = cellIterator.next();
switch (currentCell.getCellType()) {
case Cell.CELL_TYPE_STRING:
rrow.add(currentCell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
rrow.add(String.valueOf(currentCell.getNumericCellValue()));
break;
}
}
resultList.add(rrow);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
}
java.lang.NullPointerException
at ReadExcel.readExcelToList(ReadExcel.java:40)
at BasicCSVReader.main(BasicCSVReader.java:35)

您的resultList从未创建(它是null(。你可以通过如下定义来修复它:

public List<List<String>> resultList = new ArrayList<>();

最新更新