Search code examples
javaexcelapache-poidate-formatting

formatting dates using apache poi when passing a string object


I need to format a date cell in excel to be dd/mm/yyyy

I appreciate this is maybe not the "correct" standard, but, this is what the client wants...

The date that I am passing in to the cell is formatted yyyy-mm-dd

So,

I have this code:

Cell dateCell;
dateCell = row.createCell(3);
dateCell.setCellValue(p.getDateOfBirth());
CellStyle dateCellStyle = WorkBook.createCellStyle();
dateCellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("dd/mm/yyyy"));
dateCell.setCellStyle(dateCellStyle);

which according to this: http://www.kscodes.com/java/writing-various-date-formats-in-excel-using-poi/ (1)

I believe should work. But when I create the excel file the date is still yyyy-mm-dd

I have looked here How to set date field in excel using java apache poi library? and I notice that this uses the line

cell.setCellType(CellType.NUMERIC);

but there is no mention of this in (1)

Anybody got any idea what I am doing wrong?


Solution

  • The date that I am passing in to the cell is formatted yyyy-mm-dd

    This is the root cause of the problem. The API expects you to pass a Date object whereas you are passing a String object. You need to parse your date string into a Date object and pass the same to dateCell.setCellValue as shown below:

    Cell dateCell;
    dateCell = row.createCell(3);
    Date dateOfBirth = new SimpleDateFormat("yyyy-MM-dd").parse(p.getDateOfBirth() + "");
    dateCell.setCellValue(dateOfBirth);
    CellStyle dateCellStyle = WorkBook.createCellStyle();
    dateCellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("dd/mm/yyyy"));
    dateCell.setCellStyle(dateCellStyle);