Search code examples
pythongoogle-sheetsgoogle-sheets-apigspread

Updating multiple cells in gspread using Python


I'm Inserting values in Google Sheets but the loop doesn't go to the next cell it keeps inserting only in A1 instead of going to A1, A2, etc.

cell_list = wks.range('A1:A200')

    # wks.update('A1', data['_embedded']['events'])
    for k in data['_embedded']['events']:
        i = 0
        cell_list[i].value = k['name']
        wks.update_cells(cell_list)
        i += 1

This's an image for the data in the google sheets. Google Sheets data


Solution

  • In your script, how about the following modification?

    Modified script:

    I thought that your commented wks.update() will be able to be used.

    wks.update("A1", [[e["name"]] for e in data["_embedded"]["events"]], value_input_option="USER_ENTERED")
    

    When you want to use wks.update_cells(cell_list), in your script, the value is always put to the 1st element by i = 0. I think that this is the reason for your issue. So how about the following modification?

    cell_list = wks.range("A1:A200")
    for i, k in enumerate(data["_embedded"]["events"]):
        cell_list[i].value = k["name"]
    wks.update_cells(cell_list, value_input_option="USER_ENTERED")
    

    Reference: