POI解析自定义日期格式(标题虽然大众,但是内容绝非大众)

在项目中遇到过一种情况,导入的时间格式为 yyyy/mm/dd hh:mm:ss,这个很好弄,自定义一下日期格式,并且添加数据有效性。。。。赶着下班,暂时不废话那么多了。就是两种情况:一个是解析自定义日期,还有解释从别的地方复制过来的日期,虽然也能添加上去,但是后天解析时间数据不对。直接上代码,希望有所帮助。

// 特殊用途,处理自定义日期格式的  手动输入 及 复制值未点击 的情况。
//176为yyyy/m/d h:mm:ss  177为yyyy/mm/dd hh:mm:ss
if(cell.toString().contains("-") && (cell.getCellStyle().getDataFormat() == 176 || cell.getCellStyle().getDataFormat() == 177)){
    //输入的两种日期格式
    if (DateUtil.isCellDateFormatted(cell)) {
        // 如果是Date类型则,转化为Data格式
        // data格式是带时分秒的:2013-7-10 0:00:00    cellvalue = cell.getDateCellValue().toLocaleString();
        // data格式是不带带时分秒的:2013-7-10
        Date date = cell.getDateCellValue();
        cellvalue = DateUtils.format(date,"yyyy-MM-dd HH:mm:ss");
    } else {
        // 如果是纯数字,取得当前Cell的数值
        cellvalue = String.valueOf(cell.getNumericCellValue());
    }
    return cellvalue;
}
if(cell.toString().contains("/") && (cell.getCellStyle().getDataFormat() == 176 || cell.getCellStyle().getDataFormat() == 177)){
    //拼接复制值得两个格式
    SimpleDateFormat format =new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = null;
    try {
        date = format.parse(cell.getStringCellValue());
        cellvalue = DateUtils.format(date,"yyyy-MM-dd HH:mm:ss");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return cellvalue;
}

猜你喜欢

转载自www.cnblogs.com/bigod/p/10186955.html