首页 > 解决方案 > 使用 Python 在 Excel 中突出显示单元格

问题描述

我想用这个代码使用 python 突出显示一个单元格。

writer = pd.ExcelWriter('4.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')        
writer.save()

Num_cols = len (df10.TIME1)
print(Num_cols)
for k in range(0, Num_cols):
    a=0
    if df10["TIME1"][k]!=df10["TIME2"][k]:
        b=str(k)
        a='E'+b
        print(a)
        print(df10["TIME1"][k],df10["TIME2"][k])
        writer = pd.ExcelWriter('4.xlsx', engine='xlsxwriter')
        df10.to_excel(writer, sheet_name='Sheet1')
        workbook  = writer.book
        worksheet = writer.sheets['Sheet1']
        worksheet.conditional_format(a, {'type': '2_color_scale'})
        writer.save()

但它不适用于这段代码。如果我使用这一行

worksheet.conditional_format('E3', {'type': '2_color_scale'})

而不是这一行。E3 被突出显示。

worksheet.conditional_format(a, {'type': '2_color_scale'}) 

我的手机号码是可变的。我也尝试像这样定义“a”值,a="'"+a+"'"但我得到这样的错误AttributeError: 'NoneType' object has no attribute 'group'

感谢您的回答。

标签: excelpython-3.xpandas

解决方案


conditional_format()方法将范围作为输入。如果要将其应用于单个单元格,则将该单元格复制到如下范围内:

conditional_format('E3:E3', options)

但是,更好的方法是使用这样的数字范围:

conditional_format(2, 4, 2, 4, options)

请参阅有关conditional_format()Working with Conditional Formatting的文档。


推荐阅读