31

I have scanned this forum over and over and tried every method mentioned on here and still can't get Apache POI to change to fill background color of my excel document.

Here is my code:

errorOccured = true;
XSSFCellStyle cs = workbook.createCellStyle();
cs.setFillBackgroundColor(IndexedColors.RED.getIndex());
row.getCell(0).setCellStyle(cs);

Do you know why this wouldn't work? What is the correct way to get row.getCell(0) to be filled with red (background color)?

Thank you!

Tiny
  • 27,221
  • 105
  • 339
  • 599
Richie Episcopo
  • 383
  • 1
  • 3
  • 15

1 Answers1

65

Use foreground color instead of Background color.

 errorOccured = true;
 XSSFCellStyle style = workbook.createCellStyle();
 style.setFillForegroundColor(IndexedColors.RED.getIndex());
 style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
 row.getCell(0).setCellStyle(style);

this will fill the cell background color with RED.

Oscar Pérez
  • 4,377
  • 1
  • 17
  • 36
Sankumarsingh
  • 9,889
  • 11
  • 50
  • 74
  • Thank you for your answer, but this still is not working for me. I do not know why. I am in debug mode and I confirm that the code is executed but it does not change any color in the .xlsx workbook. Any ideas? Does it have anything to do with the fact that the cells I am trying to turn red are ALREADY filled in with yellow fill? – Richie Episcopo Jun 24 '13 at 14:19
  • 2
    Richie: In order to see the changes in the excel sheet, you need to perform Write command for this. Please confirm do the workbook.write(fileoutputstream) command executed before you have seen that in debug mode? – Sankumarsingh Jun 24 '13 at 15:20
  • I apoligize for the delayed response. That was the issue! I did not realize you have the rewrite the file! Thank you very much, Rich. – Richie Episcopo Jul 08 '13 at 15:13
  • @Sankumarsingh This issue has irritated me most... Thanks. – nilamber Dec 06 '13 at 16:36
  • 7
    this works, though it's a bit strange to change the foreground in order to change the background – cahen Nov 18 '14 at 11:42
  • 9
    setFillPattern() is a key element. – Mohamed Ennahdi El Idrissi Aug 09 '15 at 23:10
  • Thank you! 30 min took me to find this answer :) – Filip Dec 25 '15 at 14:03
  • setFillPattern is depreciated – ed22 Nov 08 '16 at 11:13
  • i could not make it work with LIght gray color as background or foreground. any help please? – DecKno Jan 16 '19 at 19:13