POI java怎么从cell中取值(包括公式)

直接使用POI获取Excel表格中的数据,会遇到各种数据类型和格式的问题,以下提供的函数解决了一些数据类型和格式的问题,如果遇到特殊情况可以使用类似方法判断。

private static String getValue(Cell cell) {
    if(cell==null){
        return "";
    }
    return getValue(cell.getCellType(), cell);
}

private static String getValue(CellType cellType, Cell cell) {
    if(cell==null){
        return "";
    }
    switch (cellType) {
        case BOOLEAN:
            return String.valueOf(cell.getBooleanCellValue());
        case NUMERIC:{
            double cur=cell.getNumericCellValue();

            String dataFormat = cell.getCellStyle().getDataFormatString();

            //处理日期格式问题
            if ("m/d/yy".equals(dataFormat)
                    || "yyyy\\-mm\\-dd".equals(dataFormat)
                    || "yyyy/m/d;@".equals(dataFormat)
                    || "yyyy\"年\"m\"月\"d\"日\";@".equals(dataFormat)) {
                Date d = DateUtil.getJavaDate(cur);
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
                return f.format(d);
            }
            //处理时间格式问题
            else if("yyyy/m/d\\ h:mm;@".equals(dataFormat)){
                Date d = DateUtil.getJavaDate(cur);
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return f.format(d);
            }
            else if("General".equals(dataFormat)){
                long longVal = Math.round(cur);
                Object inputValue = null;
                if(Double.parseDouble(longVal + ".0") == cur)
                    inputValue = longVal;
                else
                    inputValue = cur;
                return String.valueOf(inputValue);
            }
            return String.valueOf(cur);
        }
        case BLANK:
        case ERROR:
            return "";
        case STRING:
            return String.valueOf(cell.getRichStringCellValue());
        case FORMULA:
            try {
                CellType resultType = cell.getCachedFormulaResultType();
                return getValue(resultType, cell);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return String.valueOf(cell.getRichStringCellValue());
            }
    }
    return null;
}

在这里主要用到了poi的一个方法:cell.getCachedFormulaResultType(),这个方法可以获取公式计算后的数据类型,将计算后的类型当作一般类型处理就可以了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值