有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我在访问具有值的单元格时遇到空指针异常?

我正在使用ApachePOI库从EXCEL工作表中获取数据。我已经附上了突出显示黄色部分的EXCEL表。我试图从EXCEL工作表中提取所有数据,但没有从突出显示的部分获取数据。当试图访问这些单元格时,它会出现空指针异常

样本文件: Document

示例代码

FileInputStream inputStream=新的FileInputStream(文件)

        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表中提取的字段(突出显示的部分)。当您显式地尝试访问这些单元格时,将出现空指针异常


共 (1) 个答案

  1. # 1 楼答案

    无法复制这种行为。如果System.out.print(cell.getStringCellValue());抛出一个NPE,那么cell必须是null。但是cell根据您的代码不能是null,因为Row.cellIterator只在存在且不存在的单元格上迭代

    已下载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