【问题标题】:Gradient markup with Gspread Formatting带有 Gspread 格式的渐变标记
【发布时间】:2023-04-15 08:10:02
【问题描述】:

我正在使用 Gspread 格式为 Google 表格中的单元格设置背景颜色。 现在我想使用 GradientRule 来完成这个:

Conditional formatting with GradientRule

我知道我必须设置一个“最小点”和一个“最大点”,但我不知道该怎么做。

这是我目前得到的:

def color():
spr = client.open("Kleurtjes")
sheet = spr.worksheet("Tab3")

rule = ConditionalFormatRule(

    ranges=[GridRange.from_a1_range('A1:A10', sheet)],

    GradientRule=GradientRule(
        minpoint(format=CellFormat(backgroundColor=Color(255,255,255)), type='number'),
        maxpoint(format=CellFormat(backgroundColor=Color(0,128,0)), type='number')
    )
    )

rules = get_conditional_format_rules(sheet)
rules.append(rule)
rules.save()

你能帮帮我吗?

非常感谢!

【问题讨论】:

    标签: python google-sheets-api gspread


    【解决方案1】:

    我相信你的目标如下。

    • 你想实现以下情况。 (图片来自您的问题。)

    修改点:

    • 你可以在herehere分别看到GradientRule()InterpolationPoint()的脚本。
    • ConditionalFormatRule(),似乎使用了Sheets API 中batchUpdate 方法的AddConditionalFormatRuleRequest。在这种情况下,需要将颜色设置为从01。请注意这一点。

    当以上几点反映到你的脚本中时,它变成如下。

    修改脚本:

    请按如下方式修改您的脚本。

    从:
    rule = ConditionalFormatRule(
    
        ranges=[GridRange.from_a1_range('A1:A10', sheet)],
    
        GradientRule=GradientRule(
            minpoint(format=CellFormat(backgroundColor=Color(255,255,255)), type='number'),
            maxpoint(format=CellFormat(backgroundColor=Color(0,128,0)), type='number')
        )
        )
    
    到:
    rule = ConditionalFormatRule(
        ranges=[GridRange.from_a1_range('A1:A10', sheet)],
        gradientRule=GradientRule(
            maxpoint=InterpolationPoint(color=Color(1, 1, 1), type='MAX'),
            minpoint=InterpolationPoint(color=Color(0, 128 / 255, 0), type='MIN')
        )
    )
    

    注意:

    • 在此修改中,假设您已经能够通过使用带有 gspread 和 gspread_formatting 的 Sheets API 来获取和放置 Google 电子表格的值。请注意这一点。
    • 当你想实现图像上方的颜色时,例如minpoint=InterpolationPoint(color=Color(0.34117648, 0.73333335, 0.5411765), type='MIN')呢?

    参考资料:

    【讨论】:

    • 哇,你太棒了.. 完美运行。非常感谢:D
    • @Kuzco 感谢您的回复和测试。我很高兴你的问题得到了解决。也谢谢你。
    • @Tenaike 只是检查。 0, 128 / 255, 0 好像不是RGB?你使用的是什么配色方案?例如,如果我使用 1,1,1,它在 Google 表格中是白色的,而在 RGB 中它应该是黑色的。
    • @Kuzco 我不得不为我糟糕的英语水平道歉。关于你的第二个问题,我不确定我是否能正确理解你期望的结果。但是,关于使用这个请求的颜色,你可以看到this official document。例如,当RGB255, 255, 255时,这个请求需要使用255/255, 255/255, 255/255,即1, 1, 1。如果我误解了您的第二个问题,并且该官方文档对您的情况没有用,我再次道歉。
    • @Kuzco 关于For example, if I use 1,1,1 it is white in Google Sheets while it should be black in RGB.,在我的环境中,作为一个测试情况,当我测试1, 1, 1red, green, blue 到单元格的背景颜色时,得到了白色背景。使用0, 0, 0时,得到黑色背景。我无法复制你的情况。对此我深表歉意。