我们如何使用 XLSXWriter 中的 conditional_format() 函数根据多个条件突出显示单个单元格?

How can we use conditional_format() function from XLSXWriter to highlight a single cell based on multiple conditions?

我正在尝试编写一个代码,将 excel sheet 作为输入并将输出写入新的 excel sheet。输入是没有突出显示的相同文件。 要考虑的条件 1. 如果大于 80,则用黄色突出显示 'marks' 列中的单元格 2. 以下 3 是案例 2 的假设: 2.1.对于列 Div_No 'B' 和列 name 'v,如果值为 marks == CGPA 的值然后用黄色突出显示 CGPA 2.2.对于列 Div_No 'B' 和列 name 'v' 如果 marks > CGPA 的值然后用绿色突出显示 CGPA 2.3.对于列 Div_No 'B' 和列 name 'v' 如果 marks < CGPA 的值然后用红色突出显示 CGPABelow is the image showing the required output in excel

我认为 Excel 的内置条件格式无法做到这一点。但是可以使用 pandas 和 for 循环。我不知道这是否对您有帮助,因为列 'CGPA' 上的格式不会遵循您在创建文件后所做的任何更改,但至少您可以在创建文件时对其进行格式化。我会这样做:

import pandas as pd

# Create your dataframe
df = pd.DataFrame({'Div_No': ['A','A','A','A','B','B','B','C','C'],
                   'Roll_no': [x for x in range(1,10)],
                   'name': ['a','b','g','s','v','v','v','v','k'],
                   'marks': [54,60,54,67,43,88,54,91,66],
                   'CGPA': [54,61,53,66,46,88,51,90,65]})

# Capture the index number where it fulfils your criteria
# 1st column must equal to B, 3rd column must equal to v
rows_that_fulfil_criteria = df.index[(df['Div_No']=='B') & (df['name']=='v')]

# Kickstart the xlsxwriter
writer = pd.ExcelWriter("test.xlsx", engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Define the formats for the conditional formating
cell_format_red = workbook.add_format({'bg_color': 'red'})
cell_format_yellow = workbook.add_format({'bg_color': 'yellow'})
cell_format_green = workbook.add_format({'bg_color': 'green'})

# Conditional formatting for column marks is easy, just use the built in
worksheet.conditional_format('D2:D1048576', {'type': 'cell', 'criteria': '>',
                              'value': 80, 'format': cell_format_yellow})

# Conditional formatting for column CGPA
# If it matches the index number that we captured earlier then
# compare the values between columns marks and CGPA
for row in rows_that_fulfil_criteria:
    if df.iloc[row,3] == df.iloc[row,4]:
        worksheet.write(row+1, 4, df.iloc[row,4], cell_format_yellow)
    elif df.iloc[row,3] > df.iloc[row,4]:
        worksheet.write(row+1, 4, df.iloc[row,4], cell_format_green)
    elif df.iloc[row,3] < df.iloc[row,4]:
        worksheet.write(row+1, 4, df.iloc[row,4], cell_format_red)

writer.save()