Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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:

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

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:

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

Is there any reason you don't use nuget.org/packages/NPOI package? Dotnetcore.npoi hasn't been maintained for a long time (at least 4 years). – Tony Qu Jan 23, 2022 at 8: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, 2022 at 9: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 tonyqus.medium.com/…. – Tony Qu Feb 4, 2022 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 4, 2022 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, 2022 at 22:47

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.