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)
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)
创建电子表格的api引用位于https://developers.google.com/sheets/reference/rest/v4/spreadsheets/create。
创建新电子表格的代码段如下所示。
(2016年7月)BossyLobster的回答仍然有效(因为驱动器API v2尚未被弃用)。然而,下面是更现代的方法做同样的事情和一些视频帮助理解:
下面两个示例的授权模板
注意:要创建API项目和OAuth2凭据并将这些凭据下载到
client_secret.json
(或client_id.json
)文件,请转到Google Developers Console。创建新的/空白工作表w/Google Drive APIv3(&v2)
创建新的/空白工作表w/Google Sheets APIv4
现在你可能会问:“为什么有两种不同的方法来创建一个空白页?”简而言之,Sheets API主要用于面向电子表格的操作,即插入数据、读取电子表格行、单元格格式、创建图表、添加透视表等,而不是像create/delete和import/export这样的面向文件的请求,其中Drive API是正确的。碰巧create两者都有,所以有两种方法。
通过将MIME type设置为
application/vnd.google-apps.spreadsheet
,可以使用Drive API完成此操作:要在Python中执行此操作:
去Google APIs Explorer试一试!
相关问题 更多 >
编程相关推荐