正如许多其他人指出的那样,我最初的答案有些过时了。所以这是我为 Google 电子表格 API v4 更新的答案。现在有一种获取 gid 的方法,但我们不能使用驱动器 files.export API,因为它只导出电子表格中的第一个工作表(即使您指定了 gid)。
要将所有工作表导出为 CSV 文件,您需要使用 spreadsheets.get API 获取要导出的工作表的 gid。该 API 调用返回一堆关于电子表格的信息,包括每个工作表。您可以从每个工作表的 properties.sheetId 属性中获取 gid。
一旦你有了它,你就可以建立在你选择 File->Download As->CSV 时 Sheets 使用的相同 URL。您可以从电子表格中获取 data.spreadsheetUrl 值并将 /edit 替换为 /export,然后添加 gid 作为参数。您还需要在请求的 HTTP 标头中包含 Authorization Bearer <auth token>。
这是一个基于 quickstart 示例的 Python 脚本,它下载具有指定 ID 的电子表格的所有工作表。您需要将 <spreadsheet id> 替换为您有权访问的电子表格的 ID:
import apiclient.discovery
import httplib2
import oauth2client.file
import oauth2client.tools
import re
import requests
import shutil
import urllib.parse
SCOPES = 'https://www.googleapis.com/auth/drive.readonly'
SPREADSHEET_ID = '<spreadsheet id>'
store = oauth2client.file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = oauth2client.client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = oauth2client.tools.run_flow(flow, store)
service = apiclient.discovery.build('sheets', 'v4', http=creds.authorize(httplib2.Http()))
result = service.spreadsheets().get(spreadsheetId = SPREADSHEET_ID).execute()
urlParts = urllib.parse.urlparse(result['spreadsheetUrl'])
path = re.sub("\/edit$", '/export', urlParts.path)
urlParts = urlParts._replace(path=path)
headers = {
'Authorization': 'Bearer ' + creds.access_token,
}
for sheet in result['sheets']:
params = {
'id': SPREADSHEET_ID,
'format': 'csv',
'gid': sheet['properties']['sheetId'],
}
queryParams = urllib.parse.urlencode(params)
urlParts = urlParts._replace(query=queryParams)
url = urllib.parse.urlunparse(urlParts)
response = requests.get(url, headers = headers)
filePath = '/tmp/foo-%s.csv' % (+ params['gid'])
with open(filePath, 'wb') as csvFile:
csvFile.write(response.content)