Reputation: 91
I am creating an excel report using pandas xlswriter module. Below the code-snippet for the same.
number_rows = len(df.index)
//df is dataframe
writer = pd.ExcelWriter("Report_1.xlsx",engine='xlsxwriter')
df.to_excel(writer,"report")
workbook = writer.book
worksheet = writer.sheets['report']
# Define range for the color formatting
color_range = "A2:F{}".format(number_rows+1)
format1 = workbook.add_format({'bg_color': '#FFC7CE',
'font_color': '#9C0006'})
worksheet.conditional_format(color_range, {'type': 'text',
'criteria' : 'containing',
'value': 'SUCCESS',
'format': format1})
I want to highlight a row ('bg_color': '#FFC7CE', 'font_color': '#9C0006') based on a cell value(=SUCCESS). But when I use the "conditional_format" it is applying only on that particular cell. Is there any way to apply the format to the entire row if the “criteria” matches cell value?
Upvotes: 3
Views: 9171
Reputation: 3823
I've provided a fully reproducible example below that makes use of the INDIRECT()
function from Excel (Link here). Please note that I've set the range as $A$1:$B$6
but you can extend this to a different range if you have more columns.
import pandas as pd
df = pd.DataFrame({"Name": ['A', 'B', 'C', 'D', 'E'],
"Status": ['SUCCESS', 'FAIL', 'SUCCESS', 'FAIL', 'FAIL']})
number_rows = len(df.index) + 1
writer = pd.ExcelWriter('Report_1.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'bg_color': '#FFC7CE',
'font_color': '#9C0006'})
worksheet.conditional_format("$A$1:$B$%d" % (number_rows),
{"type": "formula",
"criteria": '=INDIRECT("B"&ROW())="SUCCESS"',
"format": format1
}
)
workbook.close()
with expected output in excel:
Upvotes: 7