`

POI读取带有公式的Excel单元格

 
阅读更多
来自:http://blog.csdn.net/cuihaiyang/article/details/7193027
private static String getStringCellValue(Cell cell) {// 获取单元格数据内容为字符串类型的数据 
        String strCell = ""; 
        if (cell == null) { 
            return ""; 
        } 
        switch (cell.getCellType()) { 
        case Cell.CELL_TYPE_FORMULA: 
            // cell.getCellFormula(); 
            try { 
            /*
             * 此处判断使用公式生成的字符串有问题,因为HSSFDateUtil.isCellDateFormatted(cell)判断过程中cell
             * .getNumericCellValue();方法会抛出java.lang.NumberFormatException异常
             */ 
             if (HSSFDateUtil.isCellDateFormatted(cell)) { 
                Date date = cell.getDateCellValue(); 
                strCell = (date.getYear() + 1900) + "-" + (date.getMonth() + 1) +"-" + date.getDate(); 
                break; 
             } else { 
                strCell = String.valueOf(cell.getNumericCellValue()); 
             } 
             } catch (IllegalStateException e) { 
                strCell = String.valueOf(cell.getRichStringCellValue()); 
             } 
            break; 
        case Cell.CELL_TYPE_STRING: 
            strCell = cell.getStringCellValue(); 
            break; 
        case Cell.CELL_TYPE_NUMERIC: 
            if (HSSFDateUtil.isCellDateFormatted(cell)) { 
                strCell = getDateCellValue(cell); 
                break; 
            } else { 
                strCell = String.valueOf(cell.getNumericCellValue()); 
                break; 
            } 
        case Cell.CELL_TYPE_BOOLEAN: 
            strCell = String.valueOf(cell.getBooleanCellValue()); 
            break; 
        case Cell.CELL_TYPE_BLANK: 
            strCell = ""; 
            break; 
        default: 
            strCell = ""; 
            break; 
        } 
        return strCell; 
    } 
这个方法在导入没有公式的Excel时没有问题,今天遇到含有公式的Excel,如图:


报错信息如下:



经调试发现HSSFDateUtil.isCellDateFormatted(cell)判断过程中会执行cell.getNumericCellValue();方法,字符串“201201FSSH300466”在转换成数字的时候出错了,在网上搜了一下,大多数的解决方法是:

[java] view plaincopy
case HSSFCell.CELL_TYPE_FORMULA: 
try { 
     value = String.valueOf(cell.getNumericCellValue()); 
} catch (IllegalStateException e) { 
     value = String.valueOf(cell.getRichStringCellValue()); 

break; 
经测试发现,在执行cell.getNumericCellValue()方法时还是抛出NumberFormatException异常,于是将try/catch中的方法互换:

[java] view plaincopy
case HSSFCell.CELL_TYPE_FORMULA: 
try { 
       strCell = String.valueOf(cell.getStringCellValue()); 
} catch (IllegalStateException e) { 
       strCell = String.valueOf(cell.getNumericCellValue()); 

break; 
这样对于字符串cell.getStringCellValue()方法即可取得其值,如果公式生成的是数值,使用cell.getStringCellValue()方法会抛出IllegalStateException异常,在异常处理中使用cell.getNumericCellValue();即可。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics