NPOI setting background color isn't working

Salkony picture Salkony · Jul 1, 2015 · Viewed 12.6k times · Source

I need to set and remove the background color of rows. Somewhy when I set style to the row it isn't working - there is still no background color of the row. I've tried to set the CellStyle property of the single cell and use the HSSFStyle. The result is the same - no background color. Here's the code:

        XSSFCellStyle style = (XSSFCellStyle)_myBook.CreateCellStyle();
        // Define cell style according to input color parameter
        XSSFColor colorToFill;
        switch (color)
        {
            default:
                colorToFill = new XSSFColor(Color.Gray);
                break;
        }
        style.SetFillBackgroundColor(colorToFill);
        for (int i = From; i <= To; i++)
        {
            var row = GetCreateRow(i);
            row.RowStyle = style;
        }

P.S. Document is opened in XSSF format

Answer

Grank picture Grank · Jul 7, 2015

Ah, we each had part of the answer! (Casting to XSSFCellStyle was what I was missing, because the ICellStyle doesn't have The SetFill methods so I couldn't get a custom color, only one of the indexed ones...)

There are two things you need to do:

  1. Call SetFillForegroundColor, not SetFillBackgroundColor.
  2. Set style.FillPattern = FillPattern.SolidForeground;

Apparently, fills in Excel are two-color, so when you want to change the fill, you HAVE to set a pattern, because the default is a cell with no fill and that means no FillPattern. SolidForeground is the basic fill pattern, and that means you have to set the foreground color of the fill, not the background color of the fill. A little counter-intuitive, but "Fill" is referring to "background color of the cell", so you could think of it like "SetBackgroundForegroundColor"/"SetBackgroundBackgroundColor"