[Java]ApachePOI读取Excel中的日期问题处理

2021-08-01 1113点热度 0人点赞 0条评论

使用Apache的POI读取Excel,遇到一个问题,读取Excel中的日期类型的Cell,发现读出来的是double类型的数值,如下代码:

String cellValue = cell.getCellTypeEnum() == CellType.NUMERIC ? new DecimalFormat("0.####").format(cell.getNumericCellValue()) : cell.getRichStringCellValue().toString().trim();

原来,POI里有一个关于日期的工具类org.apache.poi.hssf.usermodel.HSSFDateUtil,可以使用

HSSFDateUtil.isCellDateFormatted(XSSFCell) 判断是否是日期类型,然后利用HSSFDateUtil.getJavaDate()来得到Date类型的值

下面给出我的工具方法,得到cell的值:

public static String getCellStringValue(XSSFCell cell) {
    if (cell == null) {
        return "";
    }
    if (cell.getCellTypeEnum() == CellType.BLANK) {
        return "";
    }
    if (cell.getCellTypeEnum() == CellType.FORMULA) {
        return new DecimalFormat("0.####").format(cell.getNumericCellValue());
    }
    if (cell.getCellTypeEnum() != CellType.NUMERIC && cell.getCellTypeEnum() != CellType.STRING) {
        return String.valueOf(cell.getCellTypeEnum());
    }
    if (HSSFDateUtil.isCellDateFormatted(cell)) {
        Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }
    return cell.getCellTypeEnum() == CellType.NUMERIC ?
            new DecimalFormat("0.####").format(cell.getNumericCellValue()) : cell.getRichStringCellValue().toString().trim();
}

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论