Iddos
Iddos

Reputation: 127

How to clear all content of a google worksheet?

I am updating a google spreadsheet with python and gspread. I am using a CSV file for source using "values_update":

    projectSheet.values_update(
    worksheetName, params={'valueInputOption': 'USER_ENTERED'},
    body={'values': list(csv.reader(open(csvName, encoding='utf-8')))}
) 

I would like to clear all content of an existing worksheet before updating the new data. I couldn’t find a straightforward method of doing that. Is there a nice way to achieve this?

Upvotes: 1

Views: 4598

Answers (2)

E_K
E_K

Reputation: 2249

The accepted solution didn't work for me but using the clear method did. So something like projectSheet.clear() then go ahead and perform the bulk update. Here is the link to the clear method https://gspread.readthedocs.io/en/latest/api.html#gspread.models.Worksheet.clear

Upvotes: 1

Tanaike
Tanaike

Reputation: 201553

  • You want to put the values after the contents of all cells on the worksheet was cleared.
  • 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?

In this answer, the contents of all cells on the worksheet is cleared using the method of batch_update of gspread and the values are put to the cleared worksheet.

Sample script:

# Clear the contents of all cells on the worksheet of "worksheetName".
sheetId = projectSheet.worksheet(worksheetName)._properties['sheetId']
body = {
    "requests": [
        {
            "deleteRange": {
                "range": {
                    "sheetId": sheetId
                },
                "shiftDimension": "ROWS"
            }
        }
    ]
}
projectSheet.batch_update(body)

projectSheet.values_update(
    worksheetName,
    params={'valueInputOption': 'USER_ENTERED'},
    body={'values': list(csv.reader(open(csvName, encoding='utf-8')))}
)

References:

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

Upvotes: 3

Related Questions