admin管理员组

文章数量:1122998

I am using Python openpyxl to update an Excel sheet that contains a table and conditional formatting. The table has a predefined style, and the conditional formatting uses a 3-color scale applied to a specific range. I am trying to:

  • Extend the table range to include a new column.
  • Apply the same table formatting to the extended range.
  • Update the conditional formatting to cover the extended range as well.

Image below is the initial Excel sheet I want to update,

and below is the code I am using

    import openpyxl
    from openpyxl.formatting.formatting import ConditionalFormattingList
    from openpyxl.formatting.rule import ColorScaleRule
         
    path = "test_colors.xlsx"
    wb = openpyxl.load_workbook(path)    
    sheet = wb["tab1"]
      
    sheet.tables["tab1_table"].ref = "A1:D4"
    
    new_rule_range = "A2:D4"
    rule = ColorScaleRule(start_type='min', start_color='00FF00',    
                          mid_type='percentile', mid_value=50, mid_color='FFFF00',    
                          end_type='max', end_color='AA4A44')         
    
    sheet.conditional_formatting=ConditionalFormattingList()    
    sheet.conditional_formatting.add(new_rule_range, rule)
        
    wb.save(path)    
    wb.close()

but once I open the Excel file I get the following warning pop-up,

if I click yes, I get the table below with the rules applied without any table formatting.

can someone help figure out the problem, and how can I resolve it?

本文标签: