Search code examples
pythongoogle-sheetsgoogle-sheets-apigspread

How to clear a range in google sheet via gspread


Hi I would like to clear a range of A3:J10000 in google sheet by using gspread.

Doing a loop like this takes too much time:

for cell in range_to_clear:
cell.value=''
sh.worksheet('WorksheetX').update_cells(range_to_clear,value_input_option='USER_ENTERED')

I found the values_clear() method but wasn't able to make it working:

range_2_delete = sh.worksheet("WorksheetX").range("A3:J10000")
sh.values_clear(range_2_delete)

The above code giving this error: AttributeError: 'list' object has no attribute 'encode'


Solution

    • You want to clear the values of range on Google Spreadsheet.
    • You want to achieve this using gspread with python.
    • You have already been able to put and get values for Spreadsheet using Sheets API.

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

    I think that the method of values_clear() can be used for your situation.

    Modified script:

    Please modify your script as follows.

    From:

    range_2_delete = sh.worksheet("WorksheetX").range("A3:J10000")
    sh.values_clear(range_2_delete)
    

    To:

    sh.values_clear("WorksheetX!A3:J10000")
    

    or

    sh.values_clear("'WorksheetX'!A3:J10000")
    

    Note:

    • This answer supposes as follows.
      • The latest version (v3.1.0) of gspread is used.
      • sh is declared. If sh is not declared, please use sh = gc.open('My poor gym results') and sh = client.open_by_key(spreadsheetId). Ref

    Reference: