Search code examples
pythongoogle-sheetsgoogle-sheets-apigspread

Using gspread to clear two coumns on google sheets


Running this following code removes all the values found in column L.

range_of_cells = worksheet.range('L:L')

for cell in range_of_cells:



    cell.value = ''



worksheet.update_cells(range_of_cells) 

How would I modify this code so that it clears another column, Column D. So I would be removing all the values on Column L and Column D.


Solution

  • I believe your goal is as follows.

    • You want to clear the multiple columns of the Spreadsheet using gspread for python.

    In this case, how about using the batchUpdate method as follows?

    Sample script:

    spreadsheetId = "###" # Please set Spreadsheet ID.
    sheetName = "Sheet1" # Please set the sheet name.
    clearColumns = [4, 12]  # These column numbers mean columns "D" and "L"
    client = gspread.authorize(creds) # Please use your authorization script.
    
    spreadsheet = client.open_by_key(spreadsheetId)
    worksheet = spreadsheet.worksheet(sheetName)
    reqs = [{
        "repeatCell": {
            "range": {
                "sheetId": worksheet.id,
                "startColumnIndex": c - 1,
                "endColumnIndex": c
            },
            "fields": "userEnteredValue"
        }
    } for c in clearColumns]
    res = spreadsheet.batch_update({"requests": reqs})
    
    • When this script is run, the cell contents of columns "D" and "L" are cleared.
    • In this script, one API call is used for clearing the multiple columns.

    References: