I'm using poi 3.14 and all I want is to set the background of the cell to be orange. I don't want a pattern filled, just a solid orange, and yet I cannot get it to work. Here's what I have:
Row row = sheet.createRow(currentRow);
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.AUTOMATIC.getIndex());
style.setFillBackgroundColor(IndexedColors.ORANGE.getIndex());
style.setFillPattern(CellStyle.ALIGN_FILL);
Cell cell = row.createCell(0);
cell.setCellValue("ABCDEFG");
cell.setCellStyle(style);
What I end up with is an orange background with small dots
pattern. On Excel's property sheet, it says I have bg=orange, fg=automatic, pattern=25% Gray
. How can I use simply a blank pattern style?
Apache POI provides three methods for changing the background color. In the CellStyle class, we can use the setFillForegroundColor, setFillPattern, and setFillBackgroundColor methods for this purpose. A list of colors is defined in the IndexedColors class. Similarly, a list of patterns is defined in FillPatternType.
Code ExplanationXSSFCellStyle style=workbook. createCellStyle(); Then style the background and foreground by setFillBackgroundColor and setFillPattern, then give the cell value and cell style.
Method SummaryMake a copy of this style. Color is optional. Get the index of the number format (numFmt) record used by this cell format. Get the background fill color.
It seems unintuitive first but the setFillForegroundColor
method actually sets the foreground color of the background fill not the text (which comes to mind first as foreground). Similarly, you need to use CellStyle.SOLID_FOREGROUND
for the fill pattern. See below for a working version.
Row row = sheet.createRow(currentRow);
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
Cell cell = row.createCell(0);
cell.setCellValue("ABCDEFG");
cell.setCellStyle(style);
You may refer to the poi user guide for more examples: http://poi.apache.org/spreadsheet/quick-guide.html#FillsAndFrills .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With