Skip to content Skip to sidebar Skip to footer

Update Cell Background Color For Google Spreadsheet Using Python

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/rest/v4/spreadsheets/

Solution 1:

  • 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:

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


Solution 2:

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
    }

Post a Comment for "Update Cell Background Color For Google Spreadsheet Using Python"