Java – Get String value, when I read from excel with Date type (apache poi)

apache-poijavasimpledateformatxssf

I have an xlsx file that I am reading with – Apache POI Library.

For example,
In some row, I have such cells values:

01-Sep-13 | 15136.00| Matt|……


My goal is:
Read all cells in the rows as String values.
But as I see, I can't read 01-Sep-13 as string,
it only represents like Date type () with cell.getDateCellValue();


1) Could I read somehow 01-Sep-13 as string: "01-Sep-13";
2) Could I convert Date value to string in case I have different date patterns (ddMMyyyy) and (dd-MMM-yy);

Code:

When I iterate over rows and cells, Apache POI analyzes each cell type:

String normalizeCellType(Cell cell) {

    switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:
           return cell.getRichStringCellValue().getString());            
        case Cell.CELL_TYPE_NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {

                Date date = cell.getDateCellValue(); ????????????
                System.out.println(date);

            } else {

                ....
            }
            break;
        case Cell.CELL_TYPE_BOOLEAN:
           return ....
        case Cell.CELL_TYPE_FORMULA:
           return ....
        default:
            System.out.println();
    }
}

Best Solution

You can get the return value for cell#getDateCellValue() and use SimpleDateFormat to covert it to a String instance

 // Create an instance of SimpleDateFormat used for formatting 
    // the string representation of date (month/day/year)
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

    // Get the date today using cell.getDateCellValue() 
    Date today = cell.getDateCellValue()       
    // Using DateFormat format method we can create a string 
    // representation of a date with the defined format.
    String reportDate = df.format(today);

You can get the value of Date in String format - 31/10/2013. Hope this helps

Related Question