Generating Excel files with Apache POI – Removed Feature: Format from /xl/styles.xml part (Styles)

The problem

Some (big) Excel files generated using Apache POI cannot be correctly open by Excel (none of the styles applied to the cells are rendered). The error message shown by Excel is the following one :

Removed Feature: Format from /xl/styles.xml part (Styles)
Repaired Records: Cell information from /xl/worksheets/sheet1.xml part
Cell information from /xl/worksheets/sheet2.xml part
Repaired Records: Cell information from /xl/worksheets/sheet3.xml part

The cause

The root cause is that Excel can handle only a limited number of cell styles by workbook; Excel 2010 for example can handle 4000 cell style by workbook (see Excel specifications and limits).

The solution

The solution is quite simple (in theory). You have to limit the number of unique instances of org.apache.poi.ss.usermodel.CellStyle used in your workbook. For this you can use the POI utility class org.apache.poi.ss.util.CellUtil.