'How can I get a list of sheets (name and "gid") in a Google spreadsheet using the Drive API?

I am trying to use Google Drive API (Python) to download some tabs of a spreadsheets file. Are the gids information in the file's metadata? What I am trying to do is (this may not be correct, please suggest) :

file_metadata = self.service.files().get(file_id=file_id).execute()
# in the following line, how can I get a download url with a gid (a tab in a spreadsheet file)
download_url = file_metadata.get('exportLinks')['text/csv']
# download the file.


Solution 1:[1]

Indeed this seems to be a duplicate of How to convert Google spreadsheet's worksheet string id to integer index (GID)?

Here is the quick answer:

def to_gid(worksheet_id):
    return int(worksheet_id, 36) ^ 31578

Solution 2:[2]

You can do this using the Spreadsheet service in Google Apps Script. It's not as convenient as having a direct API call, but at least it is possible:

  1. Call the SpreadsheetApp.openById(id) method to open the spreadsheet using the Drive file_id.
  2. Call the Spreadsheet.getSheets() method to retrieve a list of Sheet objects.
  3. For each sheet, call the Sheet.getSheetId() and Sheet.getSheetName() methods to get the name (which is what the spreadsheet user sees) and the sheetId (which is what needs to be provided in the gid= parameter when exporting).

You can use the recently-announced Apps Script Execution API to provide a REST API for your Apps Script project, which you can then call in a similar manner to the Drive API.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 kiwidrew