我正在使用apache poi库从Excel表中获取数据。我已经连接了具有黄色部分的Excel纸。我正在尝试从Excel表中提取所有数据,但我没有从突出显示的部分中获取数据。它在尝试访问这些单元时给出了无效的指针例外。
样本文档:文档
示例代码。
fileinputstream inputstream = new fileinputstream(file);
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue());
System.out.print(",");
}
System.out.println();
}
workbook.close();
inputStream.close();
运行上述程序时,您将获得某些字段不会从Excel表中提取(突出显示部分)。当您明确尝试访问这些单元格时,您将获得空指针异常。
无法再现行为。如果System.out.print(cell.getStringCellValue());
抛出NPE,则cell
必须为null
。但是cell
不能根据您的代码为null
,因为Row.cellIterator
仅在存在的单元格上迭代,而 null
。
已经下载了您的SAMPLE.xlsx
,并使用了繁忙开发人员指南中的代码 - 获取单元格内容。该代码读取所有单元格。
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.FileInputStream;
class ReadExcelExampleDataFormatter {
public static void main(String[] args) throws Exception {
Workbook wb = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));
DataFormatter formatter = new DataFormatter();
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
System.out.print(cellRef.formatAsString());
System.out.print(" - ");
// get the text that appears in the cell by getting the cell value and applying any data formats (Date, 0.00, 1.23e9, $1.23, etc)
String text = formatter.formatCellValue(cell);
System.out.println(text);
}
}
wb.close();
}
}
结果的一部分(您的第一个黄色范围):
A15 - Report
Summary
B15 - Real Estate
C15 - Count
D15 - 3
E15 - 0
F15 - 2
A16 -
B16 -
C16 - Balance
D16 - $94,263.00
E16 - $0.00
F16 - $94,263.00
A17 -
B17 -
C17 - Current
D17 - 2
E17 - 0
F17 - 2
A18 -
B18 -
C18 - Delinquent
D18 - 0
E18 - 0
F18 - 0