1

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?

  • 1
    Please look at [this](https://stackoverflow.com/a/14314913/14056755). Does this meet your needs? – Marcin Rzepecki Nov 17 '20 at 14:21
  • Thanks marcin. I think it might but my code uses XSSFWorkbook and the code mentioned uses HSSFCell etc. Do you know if the two are compatible. I believe the difference is that one creates and excel.xls file and the other an excel.xlsx file – 3rdRockSoftware Nov 17 '20 at 14:51

1 Answers1

2

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);
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Thank you for your help Sir, That worked perfectly although I used LocalDate instead of simpleDateFormat. I'm sure I read somewhere that simpleDateFormat is soon to be deprecated. Either way, you helped me see the wood for the trees. – 3rdRockSoftware Nov 18 '20 at 15:11