12

I'm having a little trouble with setting a custom font color for an XSSFWorkbook from Apache POI. When I do:

    yellow = workbook.createCellStyle();
    Font whiteFont = workbook.createFont();
    whiteFont.setColor(new XSSFColor(new Color(255, 255, 255)).getIndexed());
    yellow.setFillForegroundColor(new XSSFColor(yellowRGB));
    yellow.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
    yellow.setFont(whiteFont);

The font stays black, I'm not sure what I'm doing wrong though.

silverAndroid
  • 960
  • 3
  • 11
  • 29

2 Answers2

11

You can do whiteFont.setColor(new XSSFColor(new Color(255,255,255)));

However, there is a bug in Apache POI, where it is switching black and white. It looks like they put a 'fix' in XSSFColor.java (look at XSSFColor.correctRGB()) to correct for a problem in Excel. It's likely that Excel was fixed, but Apache POI wasn't updated.

Instead you can do: whiteFont.setColor(HSSFColor.WHITE.index) or whiteFont.setColor(IndexedColors.WHITE.index); (this is deprecated)

or if you do whiteFont.setColor(new XSSFColor(new Color(255,255,254))); it'll be really close to white.

Phill Treddenick
  • 1,340
  • 13
  • 18
  • But the problem is I have to use `getIndexed()` because `Font.setColor(short)` uses `short` as the parameter. Also, the method doesn't work at all because I thought maybe it was just for White but when I did `whiteFont.setColor(new XSSFColor(new Color(234, 17, 156)).getIndexed());`, it still stayed Black – silverAndroid Jun 29 '15 at 13:23
  • There's some problem with getIndexed(), it's likely a problem in CTColor, which is what XSSFColor is using under the hood. What version of POI are you using? You can still do `whiteFont.setColor(HSSFColor.WHITE.index)` or `whiteFont.setColor(IndexedColors.WHITE.index);` – Phill Treddenick Jun 29 '15 at 13:58
  • What is the type of your workbook? What is the full type for the Font class that you are using? (Which package?) – Phill Treddenick Jun 29 '15 at 14:00
  • 1
    XSSFWorkbook.createFont() returns an XSSFFont. You should use that. – Phill Treddenick Jun 29 '15 at 14:06
  • I'm using `POI` v3.12, the type of workbook is a .xlsx file so I'm using the `XSSFWorkbook` class, and I was using `org.apache.poi.ss.usermodel.Font` for the font class until you told me to switch to `XSSFFont` (`org.apache.poi.xssf.usermodel.XSSFFont`). However, I switched to `XSSFFont` but it still doesn't work. – silverAndroid Jun 29 '15 at 14:34
  • 1
    You don't need to use getIndexed() if you use XSSFFont. With XSSFFont you can now use any of the solutions I described in the answer. – Phill Treddenick Jun 29 '15 at 14:48
8
XSSFFont font = (XSSFFont) wb.createFont();
font.setColor(new XSSFColor( Color.decode("#7CFC00")));
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
Lin W
  • 289
  • 4
  • 4