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

ipyaggrid 0.5.4版本单元格条件着色问题求助

ipyaggrid 实现单元格值匹配的条件着色(版本0.5.4)

在ipyaggrid 0.5.4版本中,你遇到的cellStyle条件函数不生效的问题,根源在于参数传递格式错误。ag-Grid原生支持通过函数返回样式,但ipyaggrid在传递这类JS函数时,需要直接将函数以字符串形式赋值给cellStyle,而非嵌套在{'function': ...}的对象结构里。

修改后的核心代码部分

将column_defs中name列的cellStyle配置修改为如下形式:

{
    'field': 'name',
    'headerName': 'Name',
    'cellStyle': """
        function(params) {
            if (params.value === 'xyz') {
                return { 'color': 'red' };
            }
            return null;
        }
    """,
}

完整可运行代码

import pandas as pd
from ipyaggrid import Grid
from IPython.display import display

# 示例DataFrame
df = pd.DataFrame({
    'name': ['xyz', 'abc', 'xyz', 'def', 'xyz'],
    'quantity': [10, 20, 15, 5, 30],
    'price': [1.5, 2.0, 1.2, 3.3, 0.9]
})

# 定义列配置,包含name列的条件样式
column_defs = [
    {
        'field': 'name',
        'headerName': 'Name',
        'cellStyle': """
            function(params) {
                if (params.value === 'xyz') {
                    return { 'color': 'red' };
                }
                return null;
            }
        """,
    },
    { 'headerName': 'Quantity', 'field': 'quantity' },
    { 'headerName': 'Price', 'field': 'price' }
]

# Grid配置项
grid_options = {
    'columnDefs': column_defs,
    'defaultColDef': {
        'resizable': True,
        'sortable': True,
        'filter': True
    },
    'rowSelection': 'single'
}

# 创建并显示Grid
grid = Grid(grid_data=df.to_dict("records"), 
            grid_options=grid_options,
            height=180)

display(grid)

补充说明

  • 静态样式能生效是因为直接传递了样式对象,符合ipyaggrid的参数格式要求;
  • 条件样式需要传递JS函数字符串,ipyaggrid会将其解析为ag-Grid可执行的样式函数,从而根据单元格值动态返回样式。

内容的提问来源于stack exchange,提问作者data-monkey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 16:45:12