【问题标题】:Highlight a cell in excel using Python使用 Python 在 Excel 中突出显示单元格
【发布时间】:2023-03-10 21:33:02
【问题描述】:

我想通过这段代码使用 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'这样的错误

感谢您的回答。

【问题讨论】:

标签: excel python-3.x pandas


【解决方案1】:

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

conditional_format('E3:E3', options)

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

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

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

【讨论】:

    【解决方案2】:

    我稍微修改了你的代码,现在似乎可以工作了:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(np.random.randint (0,9,(5,5)))
    
    writer = pd.ExcelWriter('4.xlsx', engine='xlsxwriter')
    workbook  = writer.book
    df.to_excel(writer, sheet_name='Sheet1')
    worksheet = writer.sheets['Sheet1'] # select sheet here
    
    Num_cols = 5
    print(Num_cols)
    for k in range(0, Num_cols):
        a=0
        if df[0][k]!=df[1][k]:
            b=str(k+2) # added shift for header
            a='E'+b
            print(a)
            print(df[0][k],df[1][k])
            worksheet.conditional_format(a, {'type': '2_color_scale'})
    writer.save()
    

    如果地址使用小写或其他格式问题,可能会出现AttributeError。

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多