Search code examples
javaexcelpalettepoi-hssfhssf

Using findSimilarColor to set a Background on Excel file


I'm having a little problem using the findSimilarColor on my java code. I already read some articles from the stackoverflow that helps me get to the following code.

HSSFCellStyle style = wb.createCellStyle();

HSSFPalette palette = wb.getCustomPalette();
// get the color which most closely matches the color you want to use
HSSFColor myColor = palette.findSimilarColor(226, 0, 116); //java don't recognize this color
// get the palette index of that color 
short palIndex = myColor.getIndex();
// code to get the style for the cell goes here
style.setFillForegroundColor(palIndex);

style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);

With that, I have no problem setting a color, except with the RGB color that I'm trying to use (226, 0, 116).

For some reason, the color that show up when I open my excel file at the end is RGB (128, 0, 128).

Does anybody have any ideas why is this happening? Or an alternative solution?

Thanks for the help.


Solution

  • Is the color (226, 0, 116) defined in the object palette? You are asking for the color defined in palette that is closer to your requirement and seems that (128, 0, 128) is the closest.

    Try something like:

    HSSFColor myColor = palette.addColor(226, 0, 116);
    

    instead of asking for a similar color.