POI setting Cell Background to a Custom Color

kenny picture kenny · May 10, 2012 · Viewed 126.5k times · Source

I want to set custom color to a cell's background.
I use HSSFWorkbook (can't use anything else).

HSSFPalette palette = aWorkBook.getCustomPalette();             
Color col = new Color(backgroundColor);                     
HSSFColor myColor  = palette.addColor((byte) 10, (byte) 11, (byte) 12); 

I get this error: java.lang.RuntimeException: Could not find free color index

Answer

Vlad picture Vlad · Jun 1, 2012

You get this error because pallete is full. What you need to do is override preset color. Here is an example of function I'm using:

public HSSFColor setColor(HSSFWorkbook workbook, byte r,byte g, byte b){
    HSSFPalette palette = workbook.getCustomPalette();
    HSSFColor hssfColor = null;
    try {
        hssfColor= palette.findColor(r, g, b); 
        if (hssfColor == null ){
            palette.setColorAtIndex(HSSFColor.LAVENDER.index, r, g,b);
            hssfColor = palette.getColor(HSSFColor.LAVENDER.index);
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return hssfColor;
}

And later use it for background color:

HSSFColor lightGray =  setColor(workbook,(byte) 0xE0, (byte)0xE0,(byte) 0xE0);
style2.setFillForegroundColor(lightGray.getIndex());
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);