How to convert System.Drawing.Color to ClosedXML.Excel.XLColor in C#

4.8k Views Asked by At

I am working with ClosedXML and the background color of a specific cell could be set like the following code.

using (var workbook = new XLWorkbook())
{
    var worksheet = workbook.Worksheets.Add("Sample Sheet");
    worksheet.Cell("A1").Value = "Hello World!";
    worksheet.Cell("A1").Style.Fill.BackgroundColor = ClosedXML.Excel.XLColor.AliceBlue;
    //  Fill background color as AliceBlue.
    workbook.SaveAs("HelloWorld.xlsx");
}

My question is:

Is there appropriate method to convert System.Drawing.Color to ClosedXML.Excel.XLColor?

Any comments or suggestions are welcome.

1

There are 1 best solutions below

2
Caius Jard On BEST ANSWER

I've never used ClosedXml but the fine manual shows many ways an XLColor can be created. I picked on the first when writing this answer initially:

var c = Color.Red;
var xlc = XLColor.FromArgb(c.A, c.R, c,G, c.B);

@FrancoisBotha helpfully pointed out that there is an overload that takes the color directly:

var c = Color.Red;
var xlc = XLColor.FromColor(c);

You can see the other ways in the manual..