Java가 Excel 파일에서 잘못된 셀 데이터를 읽습니다.

엑셀 데이터를 읽는 중 오류가 발생했습니다.

在对excel单元格取数据时,如果直接进行String.value()或者直接toString(),在对有格式的单元格中取出来的数据 往往是不尽人意的
例如:excel数据中是 2023/1/1
读出来可能是 2020年一月一号
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;
    }

Supongo que te gusta

Origin blog.csdn.net/icemeco/article/details/130872752
Recomendado
Clasificación