Search code examples
c#npoi

NPOI: change font color of some (not all) text in cell


When using C# NPOI, is there a way to change the font color of only some of the text within a cell? I know you can change the font color for the entire cell. But I would like to only change the color of the last 4 character in that cell.

I know there is a way to do this in VBA:

enter image description here

However, I do not see a way to do the same thing using NPOI


Solution

  • Example for DotNetCore.NPOI:

    var newFile = @"newbook.core.xlsx";
    using (var fs = new FileStream(newFile, FileMode.Create, FileAccess.Write))
    {
        var workbook = new XSSFWorkbook();
        var sheet = workbook.CreateSheet("Sheet1");
        var rowIndex = 0;
        var row = sheet.CreateRow(rowIndex);
        var cell = row.CreateCell(0);
        var text = "this is content";
        cell.SetCellValue(text);
        var font = workbook.CreateFont();
        font.Color = HSSFColor.Blue.Index2;
        cell.RichStringCellValue.ApplyFont(text.Length - 4, text.Length, font);
        workbook.Write(fs);
    }
    

    The code also works for .NET framework and NPOI nuget package.

    Result:

    Result

    Cell has property RichStringCellValue. You can call ApplyFont method on RichStringCellValue and specify the range where the font will be applied.