空白单元格检查以避免空指针异常

时间:2016-09-22 10:18:00

标签: java excel

我的Excel表格如下:

Property_id Property_Name                               
3             Hilton                                
Season_start_date   Season_end_date MSG Sun Mon Tues Wed Thurs Fri Sat
9/16/1999            9/16/1999      fxb 100 100 100 100 100 100 100
9/16/1999            9/16/1999      fb  100 100 100 100 100 100 100
9/16/1999            9/16/1999      tfg 100 100 100 100 100 100 100

我曾使用以下代码来检测它:

            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                // Check the cell type and format accordingly

                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BLANK:
                     throw new IOException("Cell empty "+cell.getColumnIndex() + cell.getRowIndex()); 

                case Cell.CELL_TYPE_NUMERIC:
                    System.out.print(cell.getNumericCellValue() + "\t");
                    this.propertyId = cell.getNumericCellValue();
                    break;
                case Cell.CELL_TYPE_STRING:
                    System.out.print(cell.getStringCellValue() + "\t");
                    this.propertyName = cell.getStringCellValue();
                    break;
                }
            }
            ExcelToDatabase data = new ExcelToDatabase();
            if (data.existingId(propertyId) == 0){
                data.propertyDetails(propertyId, propertyName);
                data.createTable(propertyName);
            }

但是,即使是property_name旁边的单元格,此代码也会给出空白单元格。你可以告诉我在遇到空白单元时我应该用什么来抛出异常。

我也试过了:

 if (cell == null)
    {
       throw new IOException("blank cell ");  

    }

但是这不起作用..没有抛出异常

1 个答案:

答案 0 :(得分:0)

我不知道为什么你想在遇到空白单元时抛出异常。我猜你的问题可能会被解决,如果你忽略空白单元格。

switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                System.out.print(cell.getNumericCellValue() + "\t");
                this.propertyId = cell.getNumericCellValue();
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue() + "\t");
                this.propertyName = cell.getStringCellValue();
                break;
            default;
                break;

            }