pythongoogle-sheetsgoogle-sheets-apibatch-updates

Python + Google Sheet | How to Update specific cells


I'm learning how to use Google Sheet API and Python.

Firstly, I need to update specific cells in Google Sheet, not a range of cells.

I could use update_cell(), but each update will take up a Write Request, which is not optimal.

sheet_ELCSV.update_cell(str(x),1,OH_row_Side)
sheet_ELCSV.update_cell(str(x),str(PairA_Idx),str(OH_row_Executed))
sheet_ELCSV.update_cell(str(x+1),1,"Fee")
sheet_ELCSV.update_cell(str(x+1),11,str(Sum_Fee))

I read the developers guide on spreadsheets().values().update() and batchUpdate. If I'm not mistaken, they only take 1 write request. But I don't get how to do specific cells update.

ssName = sheet_ELCSV.title + '!'
cell_range = 'A2,B2,D2,A3,K3'
 
values = (
    ('Sell','-2.17','27760.0476'),
    ('Fee', '-2.38285229')
)
value_range = {
    'majorDimension' : 'ROWS',
    'values': values
}
service.spreadsheets().values().update(
    spreadsheetId = ssID,
    valueInputOption = 'USER_ENTERED',
    range = ssName + cell_range,
    body = value_range
).execute()

Any guidance is appreciated!


Solution

  • The spreadsheets.values.update is a method used for updating single range.

    A range can be a single cell in a sheet or a group of adjacent cells in a sheet.

    Here are the example of valid ranges:

    To update multiple ranges at once, you can use batchUpdate():

    Try this code below:

    batch_update_values_request_body = {
        "valueInputOption": "RAW",
        "data": [
            {
                'range': 'Sheet1!A2',
                'values': [['Sell']]
            },
            {
                'range': 'Sheet1!B2',
                'values': [['-2.17']]
            },
            {
                'range': 'Sheet1!D2',
                'values': [['27760.0476']]
            },
            {
                'range': 'Sheet1!A3',
                'values': [['Fee']]
            },
            {
                'range': 'Sheet1!K3',
                'values': [['-2.38285229']]
            },
        ]
    }
    service.spreadsheets().values().batchUpdate(
       spreadsheetId=spreadsheet_id, 
       body=batch_update_values_request_body
    ).execute()
    

    Output: Sample output

    Reference:

    batchUpdate()

    A1 Notation