Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple POI background fill issue

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?

like image 389
ergonaut Avatar asked Mar 14 '16 16:03

ergonaut


People also ask

How do I change the background color in POI?

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.

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

Code ExplanationXSSFCellStyle style=workbook. createCellStyle(); Then style the background and foreground by setFillBackgroundColor and setFillPattern, then give the cell value and cell style.

How do I use XSSFCellStyle?

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.


1 Answers

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 .

like image 64
Mustafa Avatar answered Sep 28 '22 02:09

Mustafa