Python: xlsxwriter 无条件按范围高亮单元格

Python: xlsxwriter highlight cells by range without condition

我有一个包含 3 列的数据框。 我喜欢将 a 列突出显示为橙色,b 列突出显示为绿色,c 列突出显示为黄色,但由行尾控制。

使用 xlsxwriter 我找到了用“.add_format”突出显示整个列的示例,但我不希望突出显示整个列。

如何在不使用“.conditional_format”的情况下使用 xlsxwriter 突出显示特定单元格?

df = {'a': ['','',''],
       'b':[1,2,2]
       'c':[1,2,2]}

对于 xlsxwriter,我使用 2 种不同的方式应用格式。主要是函数 set_column (如果你不介意格式扩展到文件末尾),如果我不希望格式扩展到文件末尾(例如边界线和背景颜色)。

这就是将格式应用于数据框的方法:

import pandas as pd

# Create a test df
data = {'a': ['','',''], 'b': [1,2,2], 'c': [1,2,2]}
df = pd.DataFrame(data)

# Import the file through 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
format_orange = workbook.add_format({'bg_color': 'orange'})
format_green = workbook.add_format({'bg_color': 'green'})
format_bold = workbook.add_format({'bold': True, 'align': 'center'})

# Start iterating through the columns and the rows to apply the format
for row in range(df.shape[0]):
    worksheet.write(row+1, 0, df.iloc[row,0], format_orange)

# Alternative syntax
#for row in range(df.shape[0]):
#   worksheet.write(f'A{row+2}', df.iloc[row,0], format_orange)

for row in range(df.shape[0]):
    worksheet.write(row+1, 1, df.iloc[row,1], format_green)

# Here you can use the faster set_column function as you do not apply color
worksheet.set_column('C:C', 15, format_bold)

# Finally write the file
writer.save()

输出: