5

How can I set the RGB color in cell backgroudn using class xssfworkbook using npoi?

byte[] rgb = new byte[3] { 192, 50, 90 };
XSSFCellStyle HeaderCellStyle1 = (XSSFCellStyle)wb.CreateCellStyle();
HeaderCellStyle1.SetFillForegroundColor(new XSSFColor(new Color(255, 255, 255)));

I don't want to use this pattern:

titlestyle.BottomBorderColor = IndexedColors.Grey25Percent.Index;

2 Answers 2

7
    solution of your problem is here
    
    here simply define new xssfcolor and assign it to xssfcellstyle     
    
    
 var color = new XSSFColor(new byte[] { 0,255, 0 });
 var rowstyle =(XSSFCellStyle)wb.CreateCellStyle();
 rowstyle.SetFillForegroundColor(color)
1
  • 1
    I had to add one more line to get this working in .Net Core 3.1: rowStyle.FillPattern = FillPattern.SolidForeground;
    – Amos Long
    Oct 14, 2020 at 20:06
3

You have to make sure you cast your font to XSSFFont first, IFont does not offer access to the RGB color properties of the font.

You can then set the color using an XSSColor, which can either be constructed from a byte array or a System.Drawing.Color object.

Example code, different varieties of the constructor in comments:

var wb = new XSSFWorkbook();
var sheet = wb.CreateSheet("Sheet 1");

// Create a colored font
var font = (XSSFFont) wb.CreateFont();
// var color = new XSSFColor(ColorTranslator.FromHtml("#C88C14"));
// var color = new XSSFColor(new Color(255, 255, 255));
var color = new XSSFColor(new byte[] {200, 140, 20});
font.SetColor(color);

// Create a dedicated cell style using that font 
var style = wb.CreateCellStyle();
style.SetFont(font);

// Create some cell values
var row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue("Standard text");
var cell = row.CreateCell(1);
cell.SetCellValue("Colored text");

// Apply the cellstyle we created
cell.CellStyle = style;
2
  • 1
    Paul, Doesn't this change the font color? PParmar's original question asked how to change the cell background/foreground color.
    – Amos Long
    Oct 14, 2020 at 19:38
  • 1
    @AmosLong If you check the question history, you'll find the -original- question asked specifically about the font color :-). The question was modified after I answered it, making this answer kind of obsolete. I'm leaving it up because some people seem to find it useful.
    – Paul-Jan
    Nov 3, 2020 at 12:27

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

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