4

I would like to set a custom color to a CellStyle in POI, but it doesn't seem to be getting applied.

I have the following code:

    XSSFColor color = new XSSFColor(new byte[]{ (byte) 60,
                                                (byte) 120,
                                                (byte) 216 });
    
    CellStyle style = workBook.createCellStyle();
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    style.setFillForegroundColor(color);
    
    XSSFCell cell = createCell(row, CellType.STRING, style, cellIndex);

I have the following Gradle dependencies:

implementation("org.apache.poi:poi:5.2.3")
implementation("org.apache.poi:poi-ooxml:5.2.3")

If I use a different fille pattern and do something like this: style.setFillPattern(FillPatternType.SOLID_FOREGROUND), the background gets set, but the fill pattern is, obviously, not solid.

What's the correct way to do this?

carlspring
  • 31,231
  • 29
  • 115
  • 197

2 Answers2

1

To my surprise the following works:

XSSFColor color = new XSSFColor(new byte[]{ (byte) 60,
                                            (byte) 120,
                                            (byte) 216 },
                                new DefaultIndexedColorMap());

CellStyle style = workBook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(color);

XSSFCell cell = createCell(row, CellType.STRING, style, cellIndex);

Specifying a new DefaultIndexedColorMap() seems to solve it!

carlspring
  • 31,231
  • 29
  • 115
  • 197
0

You can create Color class of Java awt to achieve this.

 XSSFCellStyle cellStyle = this.createCellStyle(workbook);
 XSSFColor colorGrey = new XSSFColor(new Color(210, 210, 210));
 cellStyle.setFillForegroundColor(colorGrey);
AnotherOne
  • 78
  • 2
  • 11