Search code examples
pythonexceldataframexlsxwriter

compare two columns and color greater in excel using python?


I came across conditional formatting https://xlsxwriter.readthedocs.io/working_with_conditional_formats.html But not sure how to implement it. I have my result saved in dataframe, i am trying to do this color formatting based on if column2> column1: color column2 else: do nothing and save the excel file. any suggestions.


Solution

  • for row in table:
        ws.write_row(i, 0, row)
    
        i += 1
        print("for i:", i)
        cell_pointer1 = "C${}".format(i) 
        cell_pointer2 = "D${}".format(i) 
        cell_pointer3 = "E${}".format(i) 
        print("cell pointer2:", format(cell_pointer2))
    
        ws.conditional_format(format(cell_pointer2) ,
            {'type':     'cell',
             'criteria': '>=',
             'value' : format(cell_pointer1),
             'format':   format2,
            })
    
    
        ws.conditional_format(format(cell_pointer2) ,
            {'type':     'cell',
             'criteria': '<',
             'value' : format(cell_pointer1),
             'format':   format1
            })
    
        ws.conditional_format(format(cell_pointer3) ,
           {'type':     'cell',
            'criteria': '>=',
            'value' : format(cell_pointer1),
            'format':   format2,
           })
    
    
        ws.conditional_format(format(cell_pointer3) ,
           {'type':     'cell',
            'criteria': '<',
            'value' : format(cell_pointer1),
            'format':   format1
           })
    

    ws.set_column(0, 0, 25)

    wb.close()