Set custom BackgroundColor of a Excel sheet cell using epplus c#
Asked Answered
D

4

88

The problem:

I am using EEPlus.

I am stuck at applying a hex color code, e.g. #B7DEE8, for a cell in my Excel sheet.

I got the following (working) code:

ws.Cells["A1:B1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
ws.Cells["A1:B1"].Style.Fill.BackgroundColor.SetColor(Color.Gray);

But I need something like the following:

ws.Cells["A1:B1"].Style.Fill.BackgroundColor.SetColor("#B7DEE8");

So my question is: is it possible to use hex color codes with EEPlus? If so, how can I do that?

Dariusdarjeeling answered 8/6, 2013 at 10:16 Comment(0)
B
142

Try this

Color colFromHex = System.Drawing.ColorTranslator.FromHtml("#B7DEE8");
ws.Cells["A1:B1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
ws.Cells["A1:B1"].Style.Fill.BackgroundColor.SetColor(colFromHex);
Baur answered 8/6, 2013 at 10:18 Comment(2)
I'm using Interop.Excel so I had to use range.Interior.Color but the color from HTML function was what I needed.Bor
System.Drawing.ColorTranslator.FromHtml is really what any one would need.Handspring
B
28

This is working well.

Dim objExcel As New ExcelPackage
Dim Sheet As ExcelWorksheet = objExcel.Workbook.Worksheets.Add("SheetName")
Sheet.Cells["A1"].Style.Fill.PatternType = Style.ExcelFillStyle.Solid
Sheet.Cells["A1"].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(170, 170, 170))
Bojorquez answered 5/12, 2013 at 20:33 Comment(0)
I
6

You are not obliged to translate a hexadecimal CSS color formula: You can simply put "0X" as a header of that number, which makes it an integer expression:

    var couleur = System.Drawing.Color.FromArgb(OXB7DEF8);
    Sheet.Cells["A1"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
    Sheet.Cells["A1"].Style.Fill.BackgroundColor.SetColor(couleur);
Inconsiderate answered 16/8, 2018 at 20:16 Comment(0)
S
1

This worked for me.

//fill column A with solid red color from hex
worksheet.Column(1).Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Column(1).Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#FF0000"));

//fill row 4 with striped orange background
worksheet.Row(4).Style.Fill.PatternType = ExcelFillStyle.DarkHorizontal;
worksheet.Row(4).Style.Fill.BackgroundColor.SetColor(Color.Orange);
Stroman answered 22/10, 2020 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.