Introduction
Apache POI-HSSF is a branch of the Apache POI project that treats Excel files. It implements Excel ’97 .xls file format. Another branch is Apache POI-XSSF/SXSSF, which deals with Excel .xlsx format. Both allow foreground and background colors to be set, but POI-HSSF has some limitations. For instance, you are forced to use a predefined palette of colors. This article will show how to overcome this limitation and customize the colors.
Standard Way of Setting Colors
To set the background color of a cell with Apache POI-HSSF we can use the following lines of code:
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setFillPattern((short)1);
cellStyle.setFillForegroundColor(new HSSFColor.BROWN().getIndex());
cell.setCellStyle(cellStyle);
The name “foreground” is somewhat misleading. To set the background color of a cell we have to set a fill pattern and the foreground color of that pattern, hence the method setFillForegroundColor. The above code creates a sheet, a row, and then a cell. Then it creates a style object, a solid fill pattern, and the fill foreground color.
We choose the color from a predefined palette, defined in the HSSFColor class. We cannot set an arbitrary color. There is still a way to set custom colors, even if it can seem a little involved. We will see it in the next section.
Custom Way of Setting Colors
The only way we can overcome the limitation in setting arbitrary colors with POI-HSSF is to customize the predefined palette. The HSSFWorkbook class has a getCustomPalette() method that returns a custom palette. We can overwrite a specific color by setting an RGB triplet to a specific color index by using the setColorAtIndex method like the following code:
HSSFPalette palette = wb.getCustomPalette();
palette.setColorAtIndex(new HSSFColor.BROWN().getIndex(), (byte)255, (byte)240, (byte)230);
cellStyle.setFillForegroundColor(new HSSFColor.BROWN().getIndex());
cellStyle.setFillPattern((short)1);
We then set the fill foreground color with the overridden index and the solid fill pattern as we did in the standard way.
Conclusion
Apache POI-HSSF does not allow a direct way to set an arbitrary background color of a cell. In this article, we have learned a more intricate way to obtain this.
