Reputation: 275
I use apache poi to write excel file with java. What I need is a way to use "directly" this format codes to format dates when writing Date variables in some excel cell, eg. something like "dddd dd/mm/yyyy".
The BuiltInFormats doesn't seem a complete collection of what I need.
I think an optimal solution would use a carefully set instance of XSSFCellStyle to achieve the goal.
Upvotes: 3
Views: 16864
Reputation: 275
I solved by using this (workbook and cell were already defined as XSSFWorkbook and XSSFCell):
CreationHelper creationHelper = workbook.getCreationHelper();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("dddd dd/mm/yyyy"));
cell.setCellStyle(cellStyle);
Upvotes: 2
Reputation: 488
I had to do this recently. Check out the following example. I'm sure it will be quite similar when using XSSF instead.
CreationHelper creationHelper = hssfWorkbook.getCreationHelper();
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat(("dd.MM.yyyy")));
HSSFCell c1 = hssfRow.createCell(0);
HSSFCellUtil.setCellStyleProperty(c1, hssfWorkbook, CellUtil.DATA_FORMAT,
HSSFDataFormat.getBuiltinFormat(("dd.MM.yyyy")));
c1.setCellStyle(cellStyle);
c1.setCellValue(HSSFDateUtil.getExcelDate(new java.util.Date()));
Upvotes: 4