1
votes

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. Does this meet your needs?marcin.programuje
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 file3rdRockSoftware

1 Answers

2
votes

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