admin管理员组

文章数量:1316351

I am reading certain Excel cell values which could have font color red (#FF0000), green (#92D050), or the cell could be empty. Based on their color, I need to assign a fixed value to another variable.

I tried to write the code below, but it doesn't work.

Var1 = ""
Var2 = ""   
if source_sheet['C11'].value == None:
    Var1 = "No Data"
elif source_sheet['C11'].font.color.rgb == "#92D050":
    Var1 = "Red"
elif source_sheet['C11'].font.color.rgb == "#FF0000":
    Var1 = "Green"

print(Var1)

Cell C11 has a numeric value with green (#92D050) font. However, the printed value is blank. What am I missing?

I am reading certain Excel cell values which could have font color red (#FF0000), green (#92D050), or the cell could be empty. Based on their color, I need to assign a fixed value to another variable.

I tried to write the code below, but it doesn't work.

Var1 = ""
Var2 = ""   
if source_sheet['C11'].value == None:
    Var1 = "No Data"
elif source_sheet['C11'].font.color.rgb == "#92D050":
    Var1 = "Red"
elif source_sheet['C11'].font.color.rgb == "#FF0000":
    Var1 = "Green"

print(Var1)

Cell C11 has a numeric value with green (#92D050) font. However, the printed value is blank. What am I missing?

Share Improve this question edited Jan 30 at 9:32 simon 5,6011 gold badge16 silver badges29 bronze badges asked Jan 30 at 5:22 beruoistberuoist 211 silver badge2 bronze badges 3
  • 1 It's better to write the line if source_sheet['C11'].value == None: as if source_sheet['C11'].value is None: Your colours are the wrong way around elif source_sheet['C11'].font.color.rgb == "#92D050": should return "Green" not "Red". If the font colour is RGB then as mentioned it will be aRGB so the value would include an alpha value and not be just 3 Hex values, e.g. '92D050' would be 'FF92D050' and RED: 'FFFF0000' though the alpha could potentially be '00' or any other hex value (but his is unlikely). And drop the hash '#' from the check. – moken Commented Jan 30 at 9:16
  • Are you absolutely sure the colour is assigned as RGB? and not a theme colour? Either way, why not actually check what the cell is returning for the font colour? – moken Commented Jan 30 at 9:18
  • You might want to add which library you are using for reading your Excel files. – simon Commented Jan 30 at 9:33
Add a comment  | 

1 Answer 1

Reset to default 1

Thanks, I was using wrong rgb codes. I just did a print of the cell font color and it directed me to the right values. I see Moken has advised the same correction.

Var1 = ""
Var2 = ""   
if source_sheet['C11'].value is None:
    Var1 = "No Data"
elif source_sheet['C11'].font.color.rgb == "FF92D050":
    Var1 = "Green"
elif source_sheet['C11'].font.color.rgb == "FFFF0000":
    Var1 = "Red"

print(Var1)

本文标签: Identify fixed font color of cell values in Excel file using PythonStack Overflow