簡體   English   中英

從excel中讀取空指針異常java XSSFCell cell = row.getCell(j);

[英]getting null pointer exception java while reading from excel XSSFCell cell = row.getCell(j);

private String[][] data;

// to read from excel file

public void readFile() throws IOException {

    // Path to the excel file
    // File datafile = new File("C:\\Users\\atomar\\Documents\test.xlsx");
    // A Buffered File Input Stream to read the data
    FileInputStream f = new FileInputStream(
            "C:\\Users\\atomar\\Documents\\test.xlsx");
    System.out.println("file found");
    // InputStream fis = new BufferedInputStream(new FileInputStream("f"));
    // We create a workbook which represents the excel file
    XSSFWorkbook book = new XSSFWorkbook(f);

    // Next a sheet which represents the sheet within that excel file
    XSSFSheet sheet = book.getSheet("Sheet1");

    // No of rows in the sheet
    int rowNum = sheet.getLastRowNum() + 1;
    System.out.println("rowNum");

    // No of columns in the sheet
    int colNum = sheet.getRow(0).getLastCellNum();

    // A Two dimensional array of Strings which represents the data in the
    // sheet
    data = new String[rowNum][colNum];
    {

        for (int i = 0; i < rowNum; i++) {
            // Get the row
            XSSFRow row = sheet.getRow(i);

        for (int j = 0; j < colNum; j++) {
            // Get the columns or cells for the first row and keep
                // looping
                // for the other rows
        XSSFCell cell = row.getCell(j);

        // Make a call to the method cellToString which actually
                // converts the cell contents to String
                data[i][j] = cellToString(cell);

            //  data[i][j] = value;

    // Here is where you write the logic to handle the data.I am
                // just printing out the contents here.

                //System.out.println("The value is " + data[i][j]);


            }
        }

在這里我叫那個功能

public void InterestedParty() throws InterruptedException {
    try {
        readFile();
    } catch (IOException e1) {
    }
}

收到錯誤消息:不支持這種類型的單元格,我從輸入excel文件中刪除了兩行數據,然后在其正常工作之前就開始了。 但是現在我已經完全刪除了那些行,還有問題

如果沒有數據,則XSSFCell將為null 檢查它是否為null 之后,調用cellToString()方法。

    XSSFCell cell = row.getCell(j);
    if(cell != null) {
        data[i][j] = cellToString(cell);
    } else {
        // if you would like to set value when cell is null
        row.createCell(j).setCellValue(your value);
    }

您可以有一行數據,下一行為空,然后另一行為數據。 如果未定義中間行,則可以將其視為null,因此我的建議是為行使用迭代器。
RowIteratior是一個好的開始。
同樣,一旦有了該行,就可以使用單元格迭代器遍歷單元格。 請記住,未定義的單元格將被視為null並被跳過,但是空白單元格不為null!
單元迭代器在此處記錄。
您的方法也不錯,但是在使用對象之前,您需要在每次迭代中檢查是否為空或為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM