HSSF читает пустую ячейку, получая исключение нулевого указателя

Я работаю над утилитой, которая сбрасывает содержимое листа excel в базу данных (в моем случае это postgres 9.2). Приложение работает очень гладко, когда все ячейки заполнены, но всякий раз, когда я пытаюсь запустить свой код на листе excel, который имея пустую ячейку, это дает мне ИСКЛЮЧЕНИЕ NULL POINTER. Может кто-нибудь мне помочь......?

код.... снипы...

public ArrayList fillList(int colIndex, int id, List<Cell> cells,
        String path) {
    // OrderedMap errorMap=new LinkedMap();
    String error = null;
    ArrayList<String> errorList = new ArrayList<String>();
    // errorList=null;
    try {
        FileInputStream fileIn = new FileInputStream(path);

        POIFSFileSystem fs;

        fs = new POIFSFileSystem(fileIn);

        HSSFWorkbook filename = new HSSFWorkbook(fs);
        Cell number = null;
        HSSFSheet sheet = filename.getSheetAt(0);
        Row firstRow = sheet.getRow(0);
        int flag = 0;

        String errorValue = null;

        int columnNo = colIndex;
        if (columnNo != -1) {
            for (Row row : sheet) {
                if (row.getRowNum() != 0) {
                    Cell c = row.getCell(columnNo);
                   // row.getCell(arg0, arg1)
                    // cells.add(c);
                    System.out.println(c.getCellType());
                    if (c.getCellType() == Cell.CELL_TYPE_STRING && 
                             (id == 2 || id == 3)) {
                        cells.add(c);
                    } else if (c.getCellType() == Cell.CELL_TYPE_NUMERIC
                            && id == 1) {
                        String s = row.getCell(columnNo).toString();
                        double d = Double.parseDouble(s);
                        String mob = Double.toString(d);
                        Cell sc = row.createCell((short) 2);
                        String text = NumberToTextConverter.toText(c
                                .getNumericCellValue());
                        // System.out.println(text);
                        sc.setCellValue(text);
                        cells.add(sc);
                        // Date date=c.getDateCellValue();

                    } else if (c.getCellType() == Cell.CELL_TYPE_NUMERIC && id == 4) {
                        String s = row.getCell(columnNo).toString();
                        double d = HSSFDateUtil.getExcelDate(c
                                .getDateCellValue());
                        // String date = Double.toString(d);
                        Cell sc = row.createCell((short) 2);
                        String date = new SimpleDateFormat("dd-MM-yyyy")
                                .format(c.getDateCellValue());
                        // System.out.println(text);
                        sc.setCellValue(date);
                        cells.add(sc);

                    } 
                    else if (c.getCellType() == Cell.CELL_TYPE_BLANK && id == 1   ) {
                        String s = row.getCell(columnNo).toString();
                        Cell sc = row.createCell((short)2);
                        sc.setCellValue("-");
                        cells.add(sc);

                    }
                    else {
                        switch (c.getCellType()) {
                        case Cell.CELL_TYPE_NUMERIC:
                            errorValue = Double.toString(c
                                    .getNumericCellValue());
                            break;
                        case Cell.CELL_TYPE_STRING:
                            errorValue = c.getStringCellValue();
                            break;
                        }

                        errorList.add(c.getRowIndex() + "$" + columnNo
                                + "$" + errorValue + "$" + id);
                    }
                    /*
                     * if (c == null || c.getCellType() ==
                     * Cell.CELL_TYPE_BLANK) { cells.add(c); } else {
                     * 
                     * cells.add(c);
                     * 
                     * }
                     */

                    flag = 1;
                }// if to skip 1st row
            }
        } else {
            // System.out.println("could not find column " + columnWanted +
            // " in first row of " + fileIn.toString());
        }
        return errorList;
    } catch (IOException e) {

        e.printStackTrace();
    } finally {
    }
    return errorList;
}

person Er. Junaid    schedule 25.12.2013    source источник
comment
На какой строке исключение?   -  person Dawood ibn Kareem    schedule 25.12.2013
comment
поэтому сначала проверьте ячейку, чтобы увидеть, является ли она нулевой.   -  person Scary Wombat    schedule 25.12.2013
comment
@Дэвид Уолланс System.out.println(c.getCellType()); всякий раз, когда цикл выполняется в пустой ячейке, он генерирует исключение нулевого указателя в этой строке.   -  person Er. Junaid    schedule 25.12.2013
comment
@user2310289 user2310289, я тоже пробовал с этим условием, но оно не входит в нулевое состояние   -  person Er. Junaid    schedule 25.12.2013
comment
Как вы тестировали на ноль?   -  person Scary Wombat    schedule 25.12.2013
comment
Итак, как вы заполняете переменную sheet? Похоже, вы вставляете туда нули. Если это не то, чего вы хотите, то не делайте этого. Если это то, что вы хотите, выполните нулевую проверку при извлечении значений.   -  person Dawood ibn Kareem    schedule 25.12.2013
comment
если (c == null) это условие работает, братан... спасибо за ответ ..... счастливого Рождества   -  person Er. Junaid    schedule 25.12.2013


Ответы (1)


Не зная, как вы проверяете нуль в ячейке, если он выдает NPE в определенной строке, вы должны быть готовы проверить на нуль.

  if (c == null)

Если это действительно не работает, то, конечно, вы всегда можете поймать NPE.

  try {
      cellType = c.getCellType();
  } catch (NullPointerException e) {
       // oops Null
       // do something else.
  }
person Scary Wombat    schedule 25.12.2013
comment
if (c.getCellType() == Cell.CELL_TYPE_BLANK && id == 1) { String s = row.getCell(columnNo).toString(); Ячейка sc = row.createCell((short)2); sc.setCellValue(-); ячейки.добавить(sc); } // поэтому я проверяю, пуста ли ячейка - person Er. Junaid; 25.12.2013
comment
так что смотрите мой первый код if c == null) Также, если ячейка пуста, то row.getCell(columnNo).toString(); тоже выглядит довольно опасно. - person Scary Wombat; 25.12.2013
comment
большое спасибо.... этот код работает согласно моему требованию... Еще раз спасибо и счастливого Рождества....... !!!!!!! - person Er. Junaid; 25.12.2013