Apache POI XSSFColor from hex code

Solution:

The good news is, if you are using XSSF, as opposed to HSSF, then the solution to your problem is fairly easy. You simply have to cast your style variable to XSSFCellStyle. If you do, then there is a version of setFillForegroundColor that takes an XSSFColor argument, so you need not call getIndexed(). Here is some example code:

XSSFCellStyle style = (XSSFCellStyle)cell.getCellStyle();
XSSFColor myColor = new XSSFColor(Color.RED);
style.setFillForegroundColor(myColor);

However, if you are using HSSF, then things are harder. HSSF uses a color palette, which is simply an array of colors. The short value that you pass into setFillForegroundColor is an index into the palette.

So the problem you have is converting an rgb value into a palette index. The solution you proposed, using getIndexed(), is logical, but, unfortuntately, it does work for XSSFColor the way you might suppose it should.

Fortunately, there is a solution. For the moment, let us assume you will be satisfied using one of the colors in the default palette, rather than using a custom color. In that case, you can use the HSSFPalette and HSSFColor classes to solve the problem. Here is some example code:

HSSFWorkbook hwb = new HSSFWorkbook();
HSSFPalette palette = hwb.getCustomPalette();
// get the color which most closely matches the color you want to use
HSSFColor myColor = palette.findSimilarColor(255, 0, 0);
// get the palette index of that color 
short palIndex = myColor.getIndex();
// code to get the style for the cell goes here
style.setFillForegroundColor(palIndex);

If you want to use custom colors not already in the default palette, then you have to add them to the palette. The javadoc for HSSFPalette defines the methods you can use for doing so.


For Apache POI prior to 4.0 you can simply do the following :

 XSSFColor grey = new XSSFColor(new java.awt.Color(192,192,192));
 cellStyle.setFillForegroundColor(grey);

Since POI 4.0 you have to provide the workbench IndexedColorMap:

 IndexedColorMap colorMap = workbook.getStylesSource().getIndexedColors();
 XSSFColor grey = new XSSFColor(new java.awt.Color(192,192,192), colorMap);
 cellStyle.setFillForegroundColor(grey);

Use XSSFColor for XSSFWorkbook. XSSFColor can take byte[] rgb or a java.awt.Color. See examples below:

  1.  

    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFCellStyle cellStyle = wb.createCellStyle();
    byte[] rgb = new byte[3];
    rgb[0] = (byte) 242; // red
    rgb[1] = (byte) 220; // green
    rgb[2] = (byte) 219; // blue
    XSSFColor myColor = new XSSFColor(rgb); // #f2dcdb
    cellStyle.setFillForegroundColor(myColor);
    cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    
  2. see GuenSeven's answer

    XSSFColor myColor = new XSSFColor(new java.awt.Color(242, 220, 219)); // #f2dcdb
    cellStyle.setFillForegroundColor(myColor);
    cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);