Is there a way to format cells in one column based on the cells in another column for the same row? (openpyxl)

Viewed 89

I have an Excel Workbook with a sheet that looks like this:

Label    Measure    Value
A        Cost       -23.12
A        Percentage 0.357
B        Cost       48.1
C        Location   NY
C        Cost       13

What I want to do is format the cells in the Value column based on the corresponding cells in the Measure column. In this case, if the cell reads "Cost" then the cell in the same row and in the Value column should read "$ 23.12" (applying a currency format.) The formatting for Value cells when Measure is "Percentage" should be percentage, for "Location", text.

The final result would look like:

Label    Measure    Value
A        Cost       $ -23.12
A        Percentage 35.7 %
B        Cost       $ 48.10
C        Location   NY
C        Cost       $ 13.00

I am using pandas to create this data. I would simply make these changes in the DataFrame before I export to Excel. However there is one other piece of formatting I need to do. I want to highlight all numeric cells in the Value column--green if positive and red if negative. But I don't want to touch the cells corresponding to "Location."

I can do something like this:

workbook[sheet].conditional_formatting.add('C2:C6', CellIsRule(operator='greaterThan', formula=['0'], fill=green_fill, font=green_font))
workbook[sheet].conditional_formatting.add('C2:C6', CellIsRule(operator='lessThan', formula=['0'], fill=red_fill, font=red_font))

This works for all cells in row C, but how can I do this this for the specific subset of cells I'm interested in?

0 Answers
Related