2
votes

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.

2
you can define your own data format as a short with oyu can set as xssfcellstyleXtremeBaumer

2 Answers

3
votes

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()));
1
votes

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