[Python] OpenPyXL how to test if the background of two cells are identical?

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a simple problem, all that I would like to do is compare the background colour between two cells to see if the background colours are identical or not. I have setup a quick test program with a sample spreadsheet where cells A1 and A2 have an identical background. I initially unsuccessfully attempted to use:

    import openpyxl
    from openpyxl import load_workbook
    from openpyxl.styles import Color

    excel_file = 'sample_color.xlsx'
    wb = load_workbook(excel_file)
    sh = wb['Sheet1']

    if sh['A1'].fill.bgColor.rgb == sh['A2'].fill.bgColor.rgb:
    print("Background is identical!")


    From this code I get no error but it does not successfully identify if the background of two cells are equal. When I print

    sh['A1'].fill.bgColor.rgb


    I end up with the following output:

    Values must be of type <class 'str'>


    So I have a feeling I am not comparing the right thing

    I also tried to get the colour and compare that directly through the folloiwng line of code:

    color_in_hex = sh['A1'].fill.start_color.index


    However this code only returned the hexadecimal colour code for certain colours not all the colours that I need so it's not ideal.

    The reason I am trying to do this is I am currently trying to automate the migration of an old spreadsheet system to a new format and rows with certain background colours do not need to be migrated. I was planning on having a spreadsheet of 'blacklisted' colours and compare the current rows background against all the currently selected row to decide if it should be added or not.

    Continue reading...

Compartilhe esta Página