簡體   English   中英

如何更改工作表選項卡的顏色

[英]How can I change the color of a worksheet's tab

我有一個 python 腳本,它從外部資源中提取數據並將數據添加到 Google 表格。 在大多數情況下,我一切正常,除了我想更改選項卡的顏色以表示腳本狀態。

整個過程從復制工作表中的現有選項卡開始。 默認情況下,模板選項卡具有黑色突出顯示。 然后我想將黑色更改為另一種顏色以顯示數據收集正在進行中。 完成后,根據數據結果將顏色更改為綠色或紅色。

但是我找不到如何更改顏色的工作示例。 這是我到目前為止所擁有的:

    title = 'Duplicate'
    template_id = 1000

    sheet = open_worksheet() # does all the auth/credential work
    sheet.duplicate_sheet(template_id, insert_sheet_index=0, new_sheet_name=title)
    new_tab = sheet.worksheet(title)

    body = {
        "requests": [
            {
                "updateSheetProperties": {
                    "properties": {
                        "sheetId": 1001,
                        "title": title,
                        "tabColor": {
                            "red": 1.0,
                            "green": 0.3,
                            "blue": 0.4
                        }
                    },
                    "fields": "*"
                }
            }
        ]
    }

    try:
        res = sheet.batch_update(body)
        # res = new_tab.batch_update(body)
        pprint(res)
    except gspread.exceptions.APIError as gea:
        pprint(gea.args[0], width=100)

如果我嘗試對new_tab指針運行batch_update()我得到:

dict(vr, range=absolute_range_name(self.title, vr['range']))
TypeError: string indices must be integers

如果我對整sheet運行它,我會得到:

{'code': 400,
 'message': "Invalid requests[0].updateSheetProperties: You can't delete all the rows on the sheet.",
 'status': 'INVALID_ARGUMENT'}

如何修復我的請求,以便正確更新單個選項卡?

這是指向Google Sheet APISheet 屬性的鏈接,我一直在其中查找請求的外觀。

我相信你的目標如下。

  • 您想使用 gspread 更改 Google 電子表格的標簽顏色。
  • 您想使用sheet.duplicate_sheet(template_id, insert_sheet_index=0, new_sheet_name=title)插入新工作表,並希望更改新工作表的標簽顏色。

修改點:

  • 在這種情況下,可以使用new_tab.id檢索工作表 ID。 您可以將此值用於請求正文。
  • 在您的情況下,我認為tabColor而不是*可以用作fields的值。
    • 我認為這可能是您的問題的原因。 因為當使用*時,除了tabColor之外的其他字段也會發生變化。

當以上幾點反映到您的腳本時,它變成如下。

修改后的腳本:

請按如下方式修改body並再次測試。

body = {
    "requests": [
        {
            "updateSheetProperties": {
                "properties": {
                    "sheetId": new_tab.id,
                    # "title": title, # In this case, I think that this might not be required to be used.
                    "tabColor": {
                        "red": 1.0,
                        "green": 0.3,
                        "blue": 0.4
                    }
                },
                "fields": "tabColor"
            }
        }
    ]
}

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM