I am using conditional formatting in openpyxl but got stumped trying to exclude blank cells. I have a column with numbers which I format using CellisRule. Code I use is below.
ws2.conditional_formatting.add('C3:C25',CellIsRule(operator='lessThan', formula=['85'], stopIfTrue=True, fill=redFill,font=whiteText))
ws2.conditional_formatting.add('C3:C25',CellIsRule(operator='greaterThan', formula=['89.99'], stopIfTrue=True, fill=greenFill))
ws2.conditional_formatting.add('C3:C25',CellIsRule(operator='between', formula=['85', '89.99'], stopIfTrue=True, fill=yellowFill))
I tried to use FormulaRule but got no idea to use for the formula.
Update:
Instead of using conditional formatting, using a for loop worked.
for row in ws2.iter_rows("C3:C25"):
for cell in row:
if cell.value == None:
set_stylewhite(cell)
elif cell.value >= 90:
set_stylegreen(cell)
elif cell.value <= 85:
set_stylered(cell)
else:
set_styleyellow(cell)
If you're using a formula then you should use the an expression
type rule. In general, it's always better to compose the rules and styles separately:
from openpyxl import Workbook
from openpyxl.formatting.rule import Rule
from openpyxl.styles.differential import DifferentialStyle
from openpyxl.styles import Font, PatternFill
red_text = Font(color="9C0006")
red_fill = PatternFill(bgColor="FFC7CE")
dxf = DifferentialStyle(font=red_text, fill=red_fill)
r = Rule(type="expression", dxf=dxf)
r.formula = ["NOT(ISBLANK(A1))"]
wb = Workbook()
ws = wb.active
for v in range(10):
ws.append([v])
ws['A4'] = None
ws.conditional_formatting.add("A1:A10".format(ws.max_row), r)
wb.save("sample.xlsx")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.