You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级Openpyxl至2.5.3后条件格式代码触发TypeError问题求助

Openpyxl 2.4.1 → 2.5.3: Fixing "expected MultiCellRange" TypeError in Conditional Formatting

Root Cause

Between Openpyxl 2.4.1 and 2.5.3, the conditional formatting API got a critical refactor: the conditional_formatting.add() method changed its expected input type for the cell range parameter.

In 2.4.1, you could pass a raw string (like 'A3:B10') and the library would automatically parse it into the necessary range object. But starting in 2.5.x, the method explicitly requires a CellRange or MultiCellRange instance as the first argument. Passing a string directly now triggers the TypeError you're seeing, because the library no longer handles implicit string-to-range-object conversion.

Fix Steps

You need to explicitly create a valid range object from your string expression and pass that to the add() method instead of the raw string. Here's how to implement this:

  1. Import the required range class from openpyxl's worksheet module:

    from openpyxl.worksheet.cell_range import CellRange
    

    (Use MultiCellRange instead if you're working with multiple non-contiguous ranges.)

  2. Replace your string range with a CellRange instance in the add() call. You can construct the range object first for clarity, or inline it directly:

Fixed Code Example

# Import necessary classes first
from openpyxl.worksheet.cell_range import CellRange
from openpyxl.formatting.rule import CellIsRule

# ... rest of your script ...

# Build the target cell range as a CellRange object
target_range = CellRange(f'A3:B{report_query.oli_num_of_rows + 2}')

# Pass the range object to the conditional formatting add method
ws.conditional_formatting.add(
    target_range,
    CellIsRule(
        operator='equal',
        formula=[f'{two_days_old}'],
        stopIfTrue=True,
        fill=yellow_fill
    )
)

Minor Cleanup Note

Your original code had an extra trailing comma in the format() call (format(report_query.oli_num_of_rows + 2,)). While this doesn't break functionality, removing it makes the code cleaner:

# Original (with redundant comma)
'A3:B{0}'.format(report_query.oli_num_of_rows + 2,)

# Cleaned up
'A3:B{0}'.format(report_query.oli_num_of_rows + 2)
# Or use f-string for better readability (Python 3.6+)
f'A3:B{report_query.oli_num_of_rows + 2}'

内容的提问来源于stack exchange,提问作者Emac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:17:00