简体   繁体   中英

EPPlus Excel Change cell color

I am trying to set the color of a given cell with the color of another cell (that is already colored in the template. But worksheet.Cells[row, col].Style.Fill.BackgroundColor doesn't seem to have a get property. Is it possible to do that or do I have to find the exact hexdecimal code of the color on the internet ?

EDIT

using the code in the answer, I get that error (it is written in French but it translate with what I wrote in my first comment)在此处输入图片说明

How about something like this?

//get color from this cell
var rgb = ws.Cells[1, 2].Style.Fill.BackgroundColor.Rgb;
//Convert to system.drawing.color
var color = System.Drawing.ColorTranslator.FromHtml("#" + rgb);
//set color in this cell
ws.Cells[1, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
ws.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(color);

Update: Seems that if you select a color from system colors or the palette as your fill color it works fine. If you select one of the 'Theme colors' in the fill drop down .Rgb returns an empty string

//get style
var style = ws.Cells[400, 1].Style;

//If color from System colors or palette
if (!string.IsNullOrEmpty(style.Fill.BackgroundColor.Rgb))
{
   //Convert to system.drawing.colow
   var color = System.Drawing.ColorTranslator.FromHtml("#" + style.Fill.BackgroundColor.Rgb);
   //set color in this cell
   ws.Cells[1, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
   ws.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(color);
}
else if (!string.IsNullOrEmpty(style.Fill.BackgroundColor.Theme))
{
   //No idea how to get color from Theme
}

I'm not sure it's supported... according to EPPlus Faqs :

What is NOT supported by the library (these are the most obvious features)? [...] * Themes

For anyone getting here, since I had my round of fun with EPPlus and I wasn't satisfied with the answers above:

cell.Style.Fill.BackgroundColor.LookupColor()

returns #AARRGGBB color (IE red is #FFFF0000). The part you're interesdted in is probably the last 6 digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM