使用 epplus c # 设置 Excel 工作表单元格的自定义 Background Color

问题是:

我在用 EEPlus。

我卡在应用十六进制颜色代码,例如 #B7DEE8,在我的 Excel 工作表的单元格。

我得到了以下(工作)代码:

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

但我需要这样的东西:

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

所以我的问题是: 有没有可能在 EEPlus 中使用十六进制颜色代码?如果是这样,我该怎么做?

91489 次浏览

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);

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))

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);

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);