I want to write a Pandas dataframe into Excel with formatting. For this I'm using xlsxwriter
. My question is twofold:
First, how can I apply conditional formatting to a whole column? In the examples they use specific cell-range formatting (eg.
worksheet1.conditional_format('B3:K12', ...)
), is there a way I can reference a whole column?Second, I want to mark the column B with red if it differs from column C by more than 15%. What would be the correct formula for this?
I'm currently trying the below code, which doesn't work (I don't know how to reference columns).
writer = pd.ExcelWriter('pacing.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Last year vs. current state')
#worksheet.set_column('B:B', 18, format1)
workbook = writer.book
worksheet = writer.sheets['Last year vs. current state']
format_missed = workbook.add_format({'bg_color': '#ff0000'})
format_ok = workbook.add_format({'bg_color': '#008000'})
worksheet.conditional_format('C:C', {'type': 'formula',
'criteria': '=ABS((B-C)/C) > 15',
'format': format_missed})
writer.save()
Also, I'm running Excel on a Mac, not sure if it makes any difference, but I've noticed where the Windows version uses ,
, the Mac version needs ;
for formulas. Don't know how this affects xlsxwriter
.
B:B
is the usual method to reference entire column (also in this case: test first in excel). Conditional formating is excel stuff. Maybe you want just simply check in python and format cells, instead of giving Excel the condition, range and format parameters). – Boyceboycey