How do I rename a (work)sheet in a Google Sheets spreadsheet using the API in Python?

Ilden Gemil picture Ilden Gemil · Jun 28, 2016 · Viewed 9.1k times · Source

I have been trying/looking to solve this problem for a long while. I have read the documentation for gspread and I cannot find that there is a way to rename a worksheet. Any of you know how to? I would massively appreciate it! There is indeed worksheet.title which gives the name of the worksheet, but I cannot find a way to rename the actual sheet.

Thank you in advance!

Answer

Mattia Galati picture Mattia Galati · Oct 3, 2016

This is an extraction of a library which I've coded personally:

def _batch(self, requests):
    body = {
        'requests': requests
    }
    return self._service.spreadsheets().batchUpdate(spreadsheetId=self.spreadsheetId, body=body).execute()

def renameSheet(self, sheetId, newName):
    return self._batch({
        "updateSheetProperties": {
            "properties": {
                "sheetId": sheetId,
                "title": newName,
            },
            "fields": "title",
        }
    })

I think that with a little effort, you can implement it into your code and obtain what you want. In order to make the batchUpdate call, you will need the spreadsheetId as well as the initialized service as explained in the Python QUickstart - Google Sheet API