0

I am trying to read the font colour of an Excel cell using NPOI 2.2.1 or 2.1.3.1 It doesn't matter what the font colour is NPOI is always saying that it is 8 (black). Code fragment below

    IWorkbook workbook = WorkbookFactory.Create(new FileStream(txtFileName.Text, FileMode.Open, FileAccess.Read));
    ISheet worksheet = workbook.GetSheet("sheet1");
    IRow row = worksheet.GetRow(0);
    lblFontColor.Text = row.GetCell(0).CellStyle.GetFont(workbook).Color.ToString();

Is this a bug or am I doing something wrong?

Update: This only seems to be a problem when reading .xlsx files not the older .xls files

stew
  • 87
  • 2
  • 8

2 Answers2

0

You can set any color in font background:

     hstyle =(XSSFCellStyle) wb.CreateCellStyle();
                color = new XSSFColor(new byte[] { 191,191,191});
                hstyle.VerticalAlignment = VerticalAlignment.Center;
                hstyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                hfont = (XSSFFont)wb.CreateFont();
                hfont.FontHeightInPoints = 12;
                hfont.FontName = "Calibri";
                hfont.Boldweight = (short)FontBoldWeight.Bold;
                hfont.SetColor(color);
                hstyle.SetFont(hfont);
       crow = sheet.CreateRow(rowindex);
     ccel = crow.CreateCell(0);
                ccel.SetCellValue(Title);
                ccel.CellStyle = hstyle;
Gustavo Morales
  • 2,614
  • 9
  • 29
  • 37
PParmar
  • 95
  • 2
  • 9
  • 2
    In the last NPOI version... I don't find SetColor()... the font just have a short property, called Color. – Romias Apr 02 '17 at 13:43
0

You can get the font's colour as an IColor, or as RGB (byte[3]), by getting the XSSFFont and XSSFColor, or HSSFFont and HSSFColor:

private static byte[] GetFontColourRGB(ICell cell)
{
    IWorkbook workbook = cell.Row.Sheet.Workbook;
    IFont font = cell.CellStyle.GetFont(workbook);
    if (font is XSSFFont)
    {
        return (font as XSSFFont).GetXSSFColor().RGB;
    } else if (font is HSSFFont && workbook is HSSFWorkbook)
    {
        return (font as HSSFFont).GetHSSFColor(workbook as HSSFWorkbook).RGB;
    } else
    {
        return null;
    }
}

Given the RGB value you could use a lookup-table for colour names.

Billy Brown
  • 2,272
  • 23
  • 25