2

if I need to download a specific google sheet with Python and pydrive I can use a simple command like this:

drive.CreateFile({'id':'[sheetID]}).GetContentFile('file.csv', mimetype='text/csv')

this works, but, in this case, I download in CSV only the first sheet of the Google File.

If in this file there are multiple sheets and I need to download a specific sheet, maybe by the ID that I can see in the URL "...edit#gid=111115555", how can I change the command?

I'd like to download a sheet regardless the position or the name of this one.

Can you help me?

Thanks in advance

Davide
  • 25
  • 4

1 Answers1

1

I believe your goal as follows.

  • You want to download the specific sheet in Google Spreadsheet as a CSV data.
  • You want to achieve your goal using pydrive with python.

Unfortunately, I couldn't find the method for directly achieving your goal in pydrive. So, in this answer, I would like to propose a workaround for achieving your goal. In this workaround, the access token is retrieved from the authorization script for pydrive and directly request to the endpoint using the access token. The sample script is as follows.

Sample script:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import requests

# Script for authorization of pydrive.
gauth = GoogleAuth()
gauth.LocalWebserverAuth()

# Download the specific sheet in Google Spreadsheet as a CSV data.
spreadsheetId = '###' # Please set the Spreadsheet ID.
sheetId = '###' # Please set the sheet ID. (GID)
url = 'https://docs.google.com/spreadsheets/d/' + spreadsheetId + '/gviz/tq?tqx=out:csv&gid=' + sheetId
headers = {'Authorization': 'Bearer ' + gauth.credentials.access_token}
res = requests.get(url, headers=headers)
with open('file.csv', 'wb') as f:
    f.write(res.content)
  • When above script is run, the specific sheet of sheetId in Spreadsheet of spreadsheetId is downloaded as a CSV data and create it as a file.
Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • Hi mate, thanks for your reply! Seems that this solved the problem! One question: seems that there is a charset problem, how I can specify the right charset? – Davide May 04 '21 at 14:59