0

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

kiwiwings
  • 3,386
  • 1
  • 21
  • 57
Fractal
  • 1,748
  • 5
  • 26
  • 46

1 Answers1

2

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.

user2250152
  • 14,658
  • 4
  • 33
  • 57
  • Is there any reason you don't use https://www.nuget.org/packages/NPOI/ package? Dotnetcore.npoi hasn't been maintained for a long time (at least 4 years). – Tony Qu Jan 23 '22 at 08:34
  • @TonyQu As mentioned in the answer "The code also works for .NET framework and NPOI nuget package". I've tried both nuget packages. – user2250152 Jan 23 '22 at 09:58
  • The reason I mention this is that Dotnetcore.NPOI is just a forked version of NPOI 2.2.1 and they just migrated it to .NET core but there is no further bug fixes at all. For detail, please check https://tonyqus.medium.com/the-real-history-of-dotnetcore-npoi-999bb5e140c7. – Tony Qu Feb 04 '22 at 18:49
  • Your code works because dotnetcore.NPOI is just NPOI 2.2.1 and NPOI package has supported .NET core for a long time. But the community is misleaded by the evil NCC group and they believe NPOI is just a .NET framework package, which is not true. – Tony Qu Feb 04 '22 at 18:52
  • Do you think you can change the title to Example for NPOI? As I said, they steal the code and branded it as a new package/standalone project. It's still NPOI. Nothing special. And moreover, they haven't maintained the code for at least 4 years. I have no idea why devs are still willing to use the buggy package. – Tony Qu Oct 30 '22 at 22:47