封装poi操作excel超实用的工具类

适用poi版本:5.2.2

1.行索引获取Row对象

可能sheet页对象没有创建这一行,可能为空,为空时先创建Row再返回

    public static Row safeRow(Sheet sheet,int i){
        Row row = sheet.getRow(i);
        if(row == null){
            row = sheet.createRow(i);
        }
        return row;
    }

2.列索引获取Cell对象

封装该方法的原因和上面一样,getCell可能为空

    public static Cell safeCell(Row row,int i){
        Cell cell = row.getCell(i);
        if(cell == null){
            cell = row.createCell(i);
        }
        return cell;
    }

3.读取单元格数据

excel中支持多种数据格式,分别对应java中的Double、String、Date、Boolean,根据单元格的getCellType()方法判断单元格类型,返回对应类型的数据

    private static final List<Integer> EXCEL_DATE_FORMAT_LIST = Arrays.asList(14,31,57,58);

    /**
     * 获得单元格数据
     */
    public static Object getCellValue(Cell cell, FormulaEvaluator evaluator){
        if (cell == null){ return null;}
        if(Objects.equals(cell.getCellType(),CellType.STRING)){
            return cell.getStringCellValue();
        }else if(Objects.equals(cell.getCellType(),CellType.NUMERIC)){
            if(DateUtil.isCellDateFormatted(cell)){
                return cell.getDateCellValue();
            }else if (EXCEL_DATE_FORMAT_LIST.contains((int) cell.getCellStyle().getDataFormat())) {
                // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是14,31,57,58)
                double cellValue = cell.getNumericCellValue();
                return DateUtil.getJavaDate(cellValue);
            }else {
                return NumberToTextConverter.toText(cell.getNumericCellValue());
            }
        }else if(Objects.equals(cell.getCellType(),CellType.BLANK)){
            return "";
        }else if(Objects.equals(cell.getCellType(),CellType.FORMULA)){
            CellValue value = evaluator.evaluate(cell);
            if(value.getCellType() == CellType.NUMERIC){
                return NumberToTextConverter.toText(value.getNumberValue());
            }else if(value.getCellType() == CellType.BOOLEAN){
                return String.valueOf(value.getBooleanValue());
            }else{
                return value.getStringValue();
            }

       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值