1. 程式人生 > >POI解析自定義日期格式(標題雖然大眾,但是內容絕非大眾)

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;
}