Format entire row with conditional_format using pandas xlswriter module

时间秒杀一切 提交于 2019-12-22 00:07:07

问题


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?


回答1:


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:



来源:https://stackoverflow.com/questions/48527243/format-entire-row-with-conditional-format-using-pandas-xlswriter-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!