<p><strong>(2016年7月)</strong><a href="https://stackoverflow.com/users/1068170/bossylobster">BossyLobster</a>的回答仍然有效(因为驱动器API v2尚未被弃用)。然而,下面是更现代的方法做同样的事情和一些视频帮助理解:</p>
<p><strong>下面两个示例的授权模板</strong></p>
<pre><code>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)
</code></pre>
<p>注意:要创建API项目和OAuth2凭据并将这些凭据下载到<code>client_secret.json</code>(或<code>client_id.json</code>)文件,请转到<a href="http://console.developers.google.com" rel="nofollow noreferrer">Google Developers Console</a>。</p>
<ul>
<li>要了解如何使用开发人员控制台,请参见<a href="http://youtu.be/DYAwYxVs2TI?list=PLOU2XLYxmsILOIxBRPPhgYbuSslr50KVq&index=2" rel="nofollow noreferrer">this video</a>。</li>
<li>要浏览此样板授权代码,请参见<a href="http://youtu.be/h-gBeC9Y9cE?list=PLOU2XLYxmsILOIxBRPPhgYbuSslr50KVq&index=3" rel="nofollow noreferrer">this video</a>。(注意:上面的样板文件比视频中的代码稍有更新/改进)</li>
<li>要获得使用googledriveapiv2(列出驱动器文件)的简介,请参见<a href="http://youtu.be/Z5G0luBohCg?list=PLOU2XLYxmsILOIxBRPPhgYbuSslr50KVq&index=4" rel="nofollow noreferrer">this video</a>。</li>
<li>要了解Google Drive API<em>v3</em>(上传/下载文件),请参见<a href="http://developers.googleblog.com/2016/01/google-drive-uploading-downloading.html" rel="nofollow noreferrer">this blogpost & video</a>。(注意:v2&v3并排带电。。。v2还未被弃用;v3:与v2相比,API调用更少,性能更好)</li>
<li>要了解googlesheetsapiv4(将SQL数据迁移到工作表),请参见<a href="http://developers.googleblog.com/2016/06/introducing-google-sheets-api-v4.html" rel="nofollow noreferrer">this blogpost & video</a>。</li>
</ul>
<p><strong>创建新的/空白工作表w/<a href="http://developers.google.com/drive" rel="nofollow noreferrer">Google Drive API</a>v3(&v2)</strong></p>
<pre><code># 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
</code></pre>
<p><strong>创建新的/空白工作表w/<a href="http://developers.google.com/sheets" rel="nofollow noreferrer">Google Sheets API</a>v4</strong></p>
<pre><code># 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()
</code></pre>
<p>现在你可能会问:“为什么有两种不同的方法来创建一个空白页?”简而言之,Sheets API主要用于面向电子表格的操作,即插入数据、读取电子表格行、单元格格式、创建图表、添加透视表等,而不是像create/delete和import/export这样的面向文件的请求,其中Drive API是正确的。碰巧create两者都有,所以有两种方法。</p>