I have a dataframe in Pandas that I have exported to Excel and formatted headers etc. using XLWINGS. That works like a charm. But I would like to format two columns based on their value in each cell (row), so if the value is above 0 then green and below zero then red.
I can’t seem to find that option using XLWINGS, is that possible somehow?
JavaScript
x
7
1
Dummy data:
2
3
Name Type Value (color intended)
4
Boris Sale 10 Green
5
Kurt Wareho. -5 red
6
etc.
7
Advertisement
Answer
You can loop over the cells of the particular columns (note that this might not be successful, if there are empty cells in the particular columns):
JavaScript
1
17
17
1
import xlwings as xw
2
3
path = r"test.xlsx"
4
5
with xw.App(visible=False) as app:
6
wb = xw.Book(path)
7
ws = wb.sheets[0]
8
9
for a_cell in ws["C1:D1"].expand("down"):
10
if type(a_cell.value) in [float, int]:
11
if a_cell.value > 0:
12
a_cell.color = (169, 208, 142)
13
elif a_cell.value < 0:
14
a_cell.color = (192, 0, 0)
15
wb.save(path)
16
wb.close()
17