Update cell background color for google spreadsheet using python

前端 未结 2 1002
失恋的感觉
失恋的感觉 2020-12-21 13:16

I wanna use google api to update the background color of a cell in a spreadsheet with batchupdate function. https://developers.google.com/sheets/api/reference/r

相关标签:
2条回答
  • 2020-12-21 13:42
    • You want to change the background color of the cell "A1" in the sheet name of "Sheet1" on Google Spreadsheet to red using the method of batchUpdate of Sheets API.
    • You want to achieve this using google-api-python-client with python.
    • You have already been able to get and put values for Google Spreadsheet using Sheets API.

    If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

    Sample script:

    service = build('sheets', 'v4', credentials=creds)
    
    spreadsheetId = "###"  # Please set Spreadsheet ID
    sheetId = "###"  # Please set sheet ID.
    
    body = {
      "requests": [
        {
          "updateCells": {
            "range": {
              "sheetId": sheetId,
              "startRowIndex": 0,
              "endRowIndex": 1,
              "startColumnIndex": 0,
              "endColumnIndex": 1
            },
            "rows": [
              {
                "values": [
                  {
                    "userEnteredFormat": {
                      "backgroundColor": {
                        "red": 1
                      }
                    }
                  }
                ]
              }
            ],
            "fields": "userEnteredFormat.backgroundColor"
          }
        }
      ]
    }
    res = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId, body=body).execute()
    

    Note:

    • In this case, the range is required to be written with GridRange.
      • startRowIndex: 0, endRowIndex: 1m startColumnIndex: 0, endColumnIndex: 1 means the cell "A1".

    References:

    • spreadsheets.batchUpdate
    • UpdateCellsRequest
    • CellFormat
    • GridRange
    • Python Quickstart
      • About the script for authorizing, you can see it at Python Quickstart.

    If I misunderstood your question and this was not the direction you want, I apologize.

    0 讨论(0)
  • 2020-12-21 13:45

    You can use simple basic format for changing background color of the cell :

    worksheet.format("A2:B2", {
        "backgroundColor": {
          "red": 0.0,
          "green": 0.0,
          "blue": 0.0
        }
    
    0 讨论(0)
提交回复
热议问题