我正在使用Apache POI库从EXCEL Sheet获取数据。我附上了EXCEL表格,其中突出显示黄色部分。我试图从EXCEL表中提取所有数据,但我没有从突出显示的部分获取数据。在尝试访问这些单元格时,它会给出空指针异常。
示例文件: Document
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工作表中提取的字段(突出显示的部分)。当您明确尝试访问这些单元格时,您将获得空指针异常。
答案 0 :(得分:0)
无法重现该行为。如果System.out.print(cell.getStringCellValue());
引发了NPE,则cell
必须为null
。但cell
根据您的代码不能null
,因为Row.cellIterator
仅针对存在的单元格进行迭代而不 null
。
已下载SAMPLE.xlsx
并使用了Busy Developers' Guide - Getting the cell contents中的代码。此代码可以毫无问题地读取所有单元格。
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