When we're working with dates in Apache POI, we want to make sure that they're formatted correctly.
Fortunately, it's easy to set the date format using Apache POI. In this tutorial, we'll show how to define a custom DataFormat for a date as CellStyle with Apache POI and how to use existing DataFormats.
2. Starting Point
Our starting point will be a new XSSFWorkbook, an XSSFCell, and an already-created CellStyle:
XSSFWorkbook wb = new XSSFWorkbook();
CellStyle cellStyle = wb.createCellStyle();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFCell dateCell = sheet.createRow(0).createCell(0);
Since we haven't set up our wished DataFormat yet, our Date would have been converted to a number and will be displayed as:
This way of representation is badly readable for us humans. Therefore, in the following, we'll look at how we can create a better visualization by formatting.
2. Create a Custom DataFormat
First, we need to create a new CreationHelper. With the CreationHelper, we can create a new DataFormat with a specific Format. This DataFormat is internally stored and gets referenced by a short. We've to add it to the CellStyle itself and apply the CellStyle to the Cell:
CreationHelper createHelper = wb.getCreationHelper();
short format = createHelper.createDataFormat().getFormat("m.d.yy h:mm");
After we've set up this custom CellStyle, our date will be formatted:
However, if we create a new custom DataFormat, we should always remember that an Excel workbook supports a maximum number of 65.000 cell styles. So we should always reuse existing cell styles and apply them to multiple cells whenever possible.
3. Use a Default DataFormat
As we learned, Apache POI uses shorts to link to different DataFormats. Excel already has a lot of builtin DataFormats which we can use by calling them directly by their short:
Afterward, we can get the DataFormat in a String representation with the following line of code:
In our example, we'd get the following:
The most common DataFormats are:
We should always use one of those data formats if it fits our needs because Excel will display them as one of their formats and not a custom one. This will also trigger Excel to use a localized visualization of the format.
As we can see, setting the date format using Apache POI is quick and easy but also necessary to visualize dates in a human-readable way. We should try it next time we work with dates in our spreadsheets.
The complete examples are available over on GitHub.
res – REST with Spring (eBook) (everywhere)