Python:xlsxwriter按条件突出显示单元格的范围

问题描述 投票:0回答:1

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

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

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

df = {'a': ['','',''],
       'b':[1,2,2]
       'c':[1,2,2]}
python xlsxwriter
1个回答
0
投票

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

因此,这是将格式应用于数据框的方法:

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()

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.