Search code examples
c#apache-poinpoi

NPOI: Set cell color to a custom color


How do you set the cell color to a custom color using C# NPOI? I know how to change the the color of a cell with NPOI using the color index:

XSSFCellStyle cellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
cellStyle.FillBackgroundColor = IndexedColors.LightCornflowerBlue.Index;
cellStyle.FillForegroundColor = IndexedColors.LightCornflowerBlue.Index;
cellStyle.FillPattern = FillPattern.SolidForeground;
ICell cell = CurrentRow.CreateCell(CellIndex);
cell.CellStyle = cellStyle;

However, I want to use a custom color. The IndexedColors are limited and not that useful. I've have looked around a long time now for an answer.


I found this post from years back but it doesn't seem to be relevant any longer. SetFillForegroundColor is now a short and is no longer a XSSFColor.

byte[] rgb = new byte[3] { 192, 0, 0 };
XSSFCellStyle HeaderCellStyle1 = (XSSFCellStyle)xssfworkbook.CreateCellStyle();
HeaderCellStyle1.SetFillForegroundColor(new XSSFColor(rgb));

Solution

  • I should have been using FillBackgroundXSSFColor and not FillBackgroundColor

    XSSFCellStyle cellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
    byte[] rgb = new byte[3] { 255, 221, 221 };
    XSSFColor color = new XSSFColor(rgb);
    cellStyle.FillBackgroundXSSFColor = color;
    ICell cell = CurrentRow.CreateCell(CellIndex);
    cell.CellStyle = cellStyle;