Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 583
Clay Banks Avatar asked May 03 '16 18:05

Clay Banks


People also ask

How do I change the color of a cell in Excel using Java?

Using only three methods – setFillForegroundColor, setFillPattern, and setFillBackgroundColor from the CellStyle class – we can easily change a cell's background color and fill pattern.

How do I change the background color in Apache POI?

setFillgroundColor: This method enables us to set the background color of the cell, the Apache POI dependency provides us with the Indexed color class that has all the colors.


1 Answers

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);
like image 121
rgettman Avatar answered Oct 07 '22 11:10

rgettman