Kurai Bankusu Kurai Bankusu - 7 months ago 115
Java Question

Setting RGB Colors with XSSFColor

I'm trying to set an RGB Color Value using XSSFColor

setFillForeground()
method below

XSSFWorkbook workbook= new XSSFWorkbook();
CellStyle style = workbook.createCellStyle();
Style.cloneStyleFrom(headerStyle);
Style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
XSSFColor color = new XSSFColor(new java.awt.Color(215,228,188)); //accepts a short value
style.setFillForegroundColor(color .getIndexed());

Sheet sheet = workbook.createSheet(sheetName);
Row headerRow = sheet.createRow(0);

Cell cell = headerRow.createCell(i);
cell.setCellStyle(style);


I'm passing the short value however my foreground is getting set to black no matter what the RGB value. I haven't yet discovered why this is - any ideas?

Answer

The getIndexed() method in XSSFColor has Javadocs that state that it's for backwards compatibility. Basically, XSSF has no pallette, so it's useless to set an index of color in a CellStyle.

However, XSSF has its own method of setting the foreground color in a style -- using the colors directly. Use the overload of setFillBackgroundColor that directly takes a XSSFColor. It only exists in XSSFCellStyle, not the interface CellStyle, so cast it as a XSSFCellStyle first.

((XSSFCellStyle) style).setFillForegroundColor(color);
Comments