简体   繁体   English

Python:xlsxwriter 在没有条件的情况下按范围突出显示单元格

[英]Python: xlsxwriter highlight cells by range without condition

I have a dataframe with 3 columns.我有一个包含 3 列的数据框。 I like to highlight column a as orange, column b as green, column c as yellow but controlled by end of row.我喜欢将 a 列突出显示为橙色,将 b 列突出显示为绿色,将 c 列突出显示为黄色,但由行尾控制。

using xlsxwriter I found examples for highlighting the entire column with ".add_format" but I didn't want the entire column to be highlighted.使用 xlsxwriter 我找到了使用“.add_format”突出显示整列的示例,但我不希望突出显示整列。

How can I use xlsxwriter to highlight specific cells without using ".conditional_format"?如何在不使用“.conditional_format”的情况下使用 xlsxwriter 突出显示特定单元格?

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

With xlsxwriter i am applying format using 2 different ways.使用 xlsxwriter,我使用 2 种不同的方式应用格式。 Mainly with the function set_column (if you don't mind the format expanding until the end of the file) and using for loops if i do not want the format to expand until the end of the file (for example borderlines and background colors).主要使用函数 set_column (如果您不介意将格式扩展到文件末尾)并使用 for 循环,如果我不希望格式扩展到文件末尾(例如边界线和背景颜色)。

So this is how you can apply format to your dataframe:所以这就是您可以将格式应用于数据框的方法:

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

Output:输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM