Search code examples
pythonexcelcolorsformattingopenpyxl

Why are the colours that I copy to Namedstye from a cell different in openpyxl?


I'm trying to copy the colour(background,font) of a cell to NamedStyle to apply it to a different cell in another excel in the future. Example :

tmp=NamedStyle(name="tmp")
tmp.fill=copy(cell_obj.fill)

In a different excel :

cur_wb=openpyxl.Workbook()
cur_wb.add_named_style(tmp)
cur_wb.active.cell(row=1,column=4).style=temp

This code is working fine for font colour,style,alignment. It is also working for most of the background colours except Green,Orange.

All Cells which are coloured green are leading to NamedStyle coloured orange which is leading to the target cell getting coloured orange. Similarly,all Orange coloured cells are leading to NamedStyle coloured red which is leading to the target cells getting red. Also all yellow coloured cells are not leading to Namedstyle coloured yellow, Hence these cells are not having any BG colour/white.

I'm NOT facing any issue in colours like grey,blue,dark green,dark blue.

Why is this issue happening for certain colours only?


Solution

  • I can't duplicate your issue but wonder its related to using a theme colour in Excel rather than RGB. RBG colour generally should be consistent across apps with possible minor variation, however a theme may specific to the app and could vary. This is why (one of the reasons) tranfering styles is not supported.
    When selecting a fill colour from the pallet, any of the 50 default options in Fill tab may be a theme. The Orange colour for example may be theme 9, it does have an RGB value of course but Openpyxl will only get the value 9 and not RBG value. If you were to ensure the colours were all RGB that might fix the issue.
    Anyway you could check if this seems to be the difference between what colours work and what doesn't in your sheet.

    Using the same code example with cell 'B2' as the style cell you can print out the type. Value could be 'rgb' or 'theme' (or other value).

    style_cell = ws['B2']
    fill_colour_type = style_cell.fill.fgColor.type
    print(f'Fill colour Type source cell: {fill_colour_type}') 
    

    If the type value is 'theme' then the field

    style_cell.fill.fgColor.rgb
    

    will contain the theme index number rather than a hex RGB value like 'FFE26B0A'. Try changing the colour to its RGB equivalent instead and see if that fixes the issue.