4

I'm using NPOI 2.0.6.0 in a C# project and I'm running into difficulty changing the styling. While I can affect font and cell borders I cannot change the background color.

private void buildSheet(HSSFWorkbook wb, DataTable data, string sheetName)
{
    var cHelp = wb.GetCreationHelper();
    var sheet = wb.CreateSheet(sheetName);

    HSSFFont hFont = (HSSFFont)wb.CreateFont();

    hFont.Boldweight = (short)FontBoldWeight.Bold;
    hFont.Color = HSSFColor.White.Index;
    hFont.FontHeightInPoints = 18;

    HSSFCellStyle hStyle = (HSSFCellStyle)wb.CreateCellStyle();
    hStyle.SetFont(hFont);
    hStyle.BorderBottom = BorderStyle.Medium;
    hStyle.FillBackgroundColor = HSSFColor.Black.Index;

    IRow headerRow = sheet.CreateRow(1);


    int cellCount = 1;
    foreach (string str in colHeaders)
    {
        HSSFCell cell = (HSSFCell)headerRow.CreateCell(cellCount);
        cell.SetCellValue(cHelp.CreateRichTextString((str)));
        cell.CellStyle = hStyle;

        cellCount += 1;
    }

    int rowCount = 2;
    foreach (DataRow dr in data.Rows)
    {
        var row = sheet.CreateRow(rowCount);
        for (int i = 1; i < data.Columns.Count + 1; i++)
        {
            row.CreateCell(i).SetCellValue(cHelp.CreateRichTextString((dr[i - 1]).ToString()));
        }
        rowCount += 1;
    }
}

After attaching a debugger I noticed that hStyle.FillBackgroundColor never changes from 0x0040 despite that the index of black is 8.

So essentially the question is:

  • Why would HSSFCellStyle.FillBackgroundColor not be modifiable?

1 Answer 1

15

A FillBackgroundcolor cannot be applied without also specifying the FillPattern.

i.e.

        hStyle = (HSSFCellStyle)workBook.CreateCellStyle();
        hStyle.SetFont(xFont);
        hStyle.BorderBottom = BorderStyle.Medium;
        hStyle.FillForegroundColor = IndexedColors.Black.Index;
        hStyle.FillPattern = FillPattern.SolidForeground;
2
  • 3
    your answer sets the FOREground. The question is about BACK ground. I followed what you said and got BLACK cells, even if I change the BACKGround to Yellow. I can only see a Yellow background if I change the FillPattern to FillPattern.LeastDots, which are VERY annoying!! Anybody else go a clue
    – GregJF
    May 26, 2015 at 0:47
  • 4
    @GregJF see: stackoverflow.com/questions/2803841/…
    – mitchellJ
    May 27, 2015 at 2:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.