使用Drive API在Google云端硬盘中创建空电子表格

Rag*_*van 15 python google-drive-api google-api-python-client google-sheets-api

我想在Google云端硬盘中创建一个空的Google表格(仅使用元数据创建).当我提到Google SpreadSheet API文档时,它说要使用DocumentsList API,但它已被弃用,而是要求我使用Google Drive API.在Drive API文档中,我找不到任何方法来创建空Sheet.任何人都知道如何做到这一点?

bos*_*ter 29

您可以使用Drive APIMIME类型设置为application/vnd.google-apps.spreadsheet:

要在Python中执行此操作:

from apiclient.discovery import build
service = build('drive', 'v2')

import httplib2
credentials = ... # Obtain OAuth 2.0 credentials
http = credentials.authorize(httplib2.Http())

body = {
  'mimeType': 'application/vnd.google-apps.spreadsheet',
  'title': 'Name of Spreadsheet',
}
file = service.files().insert(body=body).execute(http=http)
# or for version 3 it would be
# file = service.files().create(body=body).execute(http=http)
Run Code Online (Sandbox Code Playgroud)

转到Google API Explorer进行试用!

  • "转到Google API资源管理器进行试用吧!" (4认同)

wes*_*cpy 9

(2016年7月) BossyLobster上面的答案仍然有效(因为Drive API v2 尚未被弃用[尚未]).但是,下面是更现代的做同样事情的方式和一些视频来帮助理解:

以下两个示例的授权样板

from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools

store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
Run Code Online (Sandbox Code Playgroud)

注意:要创建API项目和OAuth2凭据以及将这些凭据下载到client_secret.json(或client_id.json)文件,请转到Google Developers Console.

  • 要了解如何使用Developers Console,请参阅此视频.
  • 要浏览此样板授权码,请参阅此视频.(注意:上面的样板比视频中的代码略微更新/改进)
  • 要获得使用Google Drive API v2(列出您的云端硬盘文件)的介绍,请参阅此视频.
  • 要了解Google Drive API v3(上传/下载文件),请参阅此博文和视频.(注意:v2和v3并排活动...... v2尚未弃用; v3:API调用较少,性能优于v2)
  • 要了解Google表格API v4(将SQL数据迁移到工作表),请参阅此博客文章和视频.

使用Google Drive API v3(&v2)创建新/空白表

# above: SCOPES = 'https://www.googleapis.com/auth/drive.file'
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
data = {
    'name': 'My new Sheet',
    'mimeType': 'application/vnd.google-apps.spreadsheet',
}
sheet = DRIVE.files().create(body=data).execute() # insert() for v2
Run Code Online (Sandbox Code Playgroud)

使用Google表格API v4 创建新/空白表格

# above: SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
SHEETS = discovery.build('sheets', 'v4', http=creds.authorize(Http()))
data = {'properties': {'title': 'My new Sheet'}}
sheet = SHEETS.spreadsheets().create(body=data).execute()
Run Code Online (Sandbox Code Playgroud)

现在您可能会问,"为什么有两种不同的方法来创建空白表?" 简而言之,Sheets API主要用于面向电子表格的操作,即插入数据,读取电子表格行,单元格格式,创建图表,添加数据透视表等,而不是面向文件的请求,如创建/删除和导入/ export,其中Drive API是正确使用的API.事实上,创造是两者兼而有之,因此有两种方法可以做到这一点.