Java读取excel文件中单元格数据不正确问题

读取excel数据有误

在对excel单元格取数据时,如果直接进行String.value()或者直接toString(),在对有格式的单元格中取出来的数据 往往是不尽人意的
例如:excel数据中是 2023/1/1
读出来可能是 2023年1月1号
date转换是有问题的 原因就是因为读取时 把格式也一起读取出来了

格式化从excel单元格中读取出来的数据

public static final String REGEX = "\n";
//getCellValue出来的数据就是去格式化之后的正确数据
private String getCellValue(Cell cell) {
        Object cellValue;
        if (cell != null) {
            cellValue = cellValue(cell);
        } else {
            cellValue = "";
        }
        return String.valueOf(cellValue);
    }

    private Object cellValue(Cell cell) {
        //判断cell类型
        Object cellValue;
        switch (cell.getCellType()) {
            case NUMERIC: {
                cellValue = date(cell);
                break;
            }
            case FORMULA: {
                cellValue = formula(cell);
                break;
            }
            case STRING: {
                cellValue = cell.getRichStringCellValue().getString().replaceAll(REGEX, " ") ;
                break;
            }
            default:
                cellValue = cell.getStringCellValue();
        }
        return cellValue;
    }

    private Object formula(Cell cell) {
        //判断cell是否为日期格式
        Object cellValue = null;
        try {
            cellValue = date(cell);
        } catch (Exception e) {
            if (e.getMessage().contains(STRING)) {
                cellValue = cell.getRichStringCellValue().getString().replaceAll(REGEX, " ");
            }
        }
        return cellValue;
    }

    private Object date(Cell cell) {
        Object cellValue;
        if (DateUtil.isCellDateFormatted(cell)) {
            cellValue = cell.getDateCellValue();
            cellValue = cellDate(cellValue);
        } else {
            //数字
            cell.setCellType(CellType.STRING);
            cellValue = cell.getRichStringCellValue();

        }
        return String.valueOf(cellValue).replaceAll(REGEX, " ");
    }

    private Object cellDate(Object cellValue) {
        DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
        cellValue = formater.format(cellValue);
        return cellValue;
    }
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值