Search code examples
pythonopenpyxlconditional-formatting

Conditional Formatting Openpyxl


Can someone help me with how to replicate this conditional formatting formula in Python using Openpyxl?

=AND(RIGHT(B$7;9)="(Message)";B8<>"";A8=C8;C8="") If true,color the cell red.


Solution

  • There are a couple of and ways to do this and lots of examples, below is one option;
    cf_range will be the cell range to apply this conditional formatting to

    from openpyxl import load_workbook
    from openpyxl.styles import fills
    from openpyxl.formatting.rule import FormulaRule
    
    work_book = load_workbook('foo.xlsx')
    sheet = work_book.active
    
    cf_range = '$A1'
    
    sheet.conditional_formatting.add(cf_range,
                                     FormulaRule(
                                         formula=["AND(RIGHT(B$7,9)=\"(Message)\";B8<>\"\";A8=C8;C8=\"\")"],
                                         fill=fills.PatternFill("solid", bgColor="FF0000"),
                                         stopIfTrue=False
                                         )
                                     )
    
    work_book.save('foo.xlsx')