Reading time values from spreadsheet using poi api

后端 未结 2 1678
闹比i
闹比i 2020-12-19 01:42

I am trying to read a date column and a time column from a spreadsheet. I am able to retireve the date column from the sheet, but not the time column.

For example,

2条回答
  •  自闭症患者
    2020-12-19 02:14

    This is my rough attempt for getting "Date-only", "Time-Only" or "Date-Time" values of POI Cells

        ...
    private String getCellValueAsString(Cell poiCell){
    
        if (poiCell.getCellType()==Cell.CELL_TYPE_NUMERIC && DateUtil.isCellDateFormatted(poiCell)) {
            //get date
            Date date = poiCell.getDateCellValue();
    
            //set up formatters that will be used below
            SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm:ss");
            SimpleDateFormat formatYearOnly = new SimpleDateFormat("yyyy");
    
            /*get date year.
            *"Time-only" values have date set to 31-Dec-1899 so if year is "1899"
            * you can assume it is a "time-only" value 
            */
            String dateStamp = formatYearOnly.format(date);
    
            if (dateStamp.equals("1899")){
                //Return "Time-only" value as String HH:mm:ss
                return formatTime.format(date);
            } else {
                //here you may have a date-only or date-time value
    
                //get time as String HH:mm:ss 
                String timeStamp =formatTime.format(date);
    
                if (timeStamp.equals("00:00:00")){
                    //if time is 00:00:00 you can assume it is a date only value (but it could be midnight)
                    //In this case I'm fine with the default Cell.toString method (returning dd-MMM-yyyy in case of a date value)
                    return poiCell.toString();
                } else {
                    //return date-time value as "dd-MMM-yyyy HH:mm:ss"
                    return poiCell.toString()+" "+timeStamp;
                }
            }
        }
    
        //use the default Cell.toString method (returning "dd-MMM-yyyy" in case of a date value)
        return poiCell.toString();
    }
    

提交回复
热议问题