Prem
Prem

Reputation: 628

How to set excel cell background color with System color in NPOI

I have an object of class Foo with attribute StatusColor being used in multiple locations. Now, I have to generate an Excel file using NPOI in which the column Status Color should have the same color as the object.

I do not know how to set System.Drawing.Color as CellStyle color, please help.

I would like something like:

class Foo{
    //Properties..
    System.Drawing.Color StatusColor {get;set;}
}

...

//Creating Status Style
var statusStyle = workbook.CreateCellStyle();
statusStyle.FillForegroundColor = fooObject.StatusColor; //Of course, it won't work.
//Is there way to convert from System.Color to HSSFColor?
statusStyle.FillPattern = FillPattern.SolidForeground;

...

//Set Style
excelCell.CellStyle = style;

In-Short: How can I convert System.Drawing.Color into HSSFColor color index?

I tried: I have written a function to convert (from Color to HSSFColor index), but not sure how many if-else have to be written.

public static short ToHSSFColorIndex(Color color)
{
    if (Color.Green.ToArgb().Equals(color.ToArgb()))
        return HSSFColor.Green.Index;
    else if (Color.Green.ToArgb().Equals(color.ToArgb()))
        return HSSFColor.LightGreen.Index;
    else if (Color.Red.ToArgb().Equals(color.ToArgb()))
        return HSSFColor.Red.Index;
    else if (Color.DarkRed.ToArgb().Equals(color.ToArgb()))
        return HSSFColor.DarkRed.Index;
    else if (Color.Gray.ToArgb().Equals(color.ToArgb()))
        return HSSFColor.Grey50Percent.Index;
    else if (Color.Blue.ToArgb().Equals(color.ToArgb()))
        return HSSFColor.Blue.Index;
    else if (Color.Yellow.ToArgb().Equals(color.ToArgb()))
        return HSSFColor.Yellow.Index;
    else if (Color.YellowGreen.ToArgb().Equals(color.ToArgb()))
        return HSSFColor.LightYellow.Index;
    else if (Color.White.ToArgb().Equals(color.ToArgb()))
        return HSSFColor.White.Index;
    else
        return HSSFColor.COLOR_NORMAL;
}

Upvotes: 2

Views: 1920

Answers (1)

You can use this:

var color = new XSSFColor(fooObject.StatusColor);
statusStyle.FillForegroundColor = color.Indexed;

Upvotes: 0

Related Questions