EPPlus Excel Change cell color

为君一笑 提交于 2020-01-02 07:06:58

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/31025464/epplus-excel-change-cell-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!