Home » excel » java – Duplicating Excel colors with Apache Poi

java – Duplicating Excel colors with Apache Poi

Posted by: admin May 14, 2020 Leave a comment


In my Excel File a macro looks for certain cell values and then changes the fillcolor.

I have all the RGB values for these colors and want to set exactly these colors when I write data with Apache POI in a file.

How can I do this ?

How to&Answers:

I had faced a problem may be similar to your problem before.
First look at this example for sure that you know the method to fill color for a cell:
It’s seem fine, but I figured out a common error that it may easily be taken. If you try to set the cell value and style in a loop, so the style declaration must be fresh every round of loop. That mean you have to reinitialize your style variable inside the loop.
It’s somehow like you put this declaration inside your loop:

    //I suppose that we have an instance named row to working on.
    XSSFCell cell = row.getCell(i);
    XSSFCellStyle style1 = wb.createCellStyle(); //create a fresh instance
    cell.setCellValue("custom XSSF colors");    //Set the cell value

    //This two line will setup the style of your cell with your needs
    style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));

    //Finally apply your style


The only way I know to add a custom color in POI is changing a default color:

Workbook wb = ...;    
wb.getCustomPalette().setColorAtIndex(HSSFColor.LIGHT_ORANGE.index, (byte) 255, (byte) 171, (byte) 115);