Using findSimilarColor to set a Background on Excel file

1k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

I just test your solutions and I get the "Could not find free color index" error. So I search a little and find out the following code to avoid this error.

HSSFPalette palette = wb.getCustomPalette();

palette.setColorAtIndex(HSSFColor.TAN.index, (byte)226, (byte)0, (byte)116);
cabecalho.setFillForegroundColor(HSSFColor.TAN.index);

It seems that I couldn't add a color to the pallete because the palette was full, so with this code I was able to overwrite the "Tan.index" to have the RGB Color that I want.

I'll try to find a better solution, but in the meanwhile this will help a lot.

Thank you once more.