使用Drive API在Google Drive中创建空电子表格

16

我想在Google Drive中创建一个只包含元数据的空白Google Sheet。当我查阅Google SpreadSheet API文档时发现,它建议使用DocumentsList API,但是该API已经被弃用,并且要求我使用Google Drive API。在Drive API文档中,我找不到任何创建空白电子表格的方法。是否有人知道如何做到这一点?


https://dev59.com/rmbWa4cB1Zd3GeqPbeA2 和 https://dev59.com/ZWgu5IYBdhLWcg3wUljt 应该会很有帮助 :D - Bolutife Ogunsola
5个回答

30
你可以使用Drive API,通过将MIME类型设置为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)

前往Google APIs Explorer尝试一下吧!


1
我该如何获取OAuth 2.0凭证? - Santosh Ghimire
4
前往Google API Explorer尝试它! - bossylobster
1
我在Google APIs Explorer中尝试并成功了。但是我想从Python代码中实现,授权部分让我很困扰。 - Santosh Ghimire
它不起作用,我能够使用"text/plain" MIME类型创建文本文件..但无法创建电子表格。 - John
感谢这个例子,不是因为问题,而是因为这是我找到的第一个用于发布模型的示例。我找到的所有文档都使用获取和列出示例。 - pfried
显示剩余2条评论

14
(2016年7月)BossyLobster的回答仍然有效(因为Drive API v2尚未被弃用)。然而,以下是更现代化的实现相同功能的方法,并附有一些视频以帮助理解:
以下是两个示例的授权样板:
from googleapiclient 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)

注意:要创建API项目和OAuth2凭据,并将这些凭据下载到client_secret.json(或client_id.json)文件中,请访问Google开发者控制台
  • 要学习如何使用开发者控制台,请参阅此视频
  • 要了解如何使用这个样板授权代码,请参阅此视频。(注意:上面的样板代码稍微更新/改进了视频中的代码)
  • 要了解如何使用Google Drive API v2(列出您的Drive文件),请参阅此视频
  • 要了解Google Drive API v3(上传/下载文件),请参阅此博文和视频。(注意:v2和v3并存... v2尚未被弃用;v3:较少的API调用,更好的性能与v2相比)
  • 要了解Google Sheets API v4(将SQL数据迁移到表格),请参阅此博文和视频
创建新的/空白表格 w/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

使用Google Sheets 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()

现在你可能会问,“为什么有两种不同的方法来创建一个空白的工作表?”简而言之,Sheets API 主要用于面向电子表格操作,例如插入数据、读取电子表格行、单元格格式化、创建图表、添加数据透视表等,而不是像创建/删除和导入/导出这样的“文件导向请求”,这时候应该使用 Drive API。巧合的是,创建操作有点两者兼而有之,这就是为什么有两种方法的原因。

我可以指定在Google Drive的哪个文件夹中创建这个电子表格吗? - João Abrantes
可以的。请查看如何操作的文档:https://developers.google.com/drive/v3/reference/files/create,寻找“parents”属性。 - wescpy

1
创建电子表格的API参考文档位于https://developers.google.com/sheets/reference/rest/v4/spreadsheets/create
创建新电子表格的代码片段如下。
String[] SCOPES = { SheetsScopes.SPREADSHEETS };

GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
        getApplicationContext(),
        Arrays.asList(SCOPES)).setBackOff(new ExponentialBackOff());
credential.setSelectedAccountName("your_google_account@gmail.com");

HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

com.google.api.services.sheets.v4.Sheets service =
    new com.google.api.services.sheets.v4.Sheets.Builder(
        transport,
        jsonFactory,
        credential)
    .setApplicationName("Google Sheets API Android Quickstart")
    .build();

Spreadsheet spreadsheet = new Spreadsheet();
SpreadsheetProperties properties = new SpreadsheetProperties();
properties.setTitle("SpreadSheetTitle");
spreadsheet.setProperties(properties);

service.spreadsheets().create(spreadsheet).execute()

2
好消息是:这使用了最新版本的Sheets API,v4。不好的消息是:OP请求一个Python示例。 - wescpy

1
你可以尝试我写的pygsheets库,它当然提供了比仅创建电子表格更多的功能。
import pygsheets

gc = pygsheets.authorize(outh_file='client_secret.json')

# Open spreadsheet and then worksheet
gc.create('my new sheet')

0

我尝试了提出的方法,但是以下代码可以工作:

# requires: uid='example@gmail.com', pass1='password', 
# name_spr='name_of_spreadsheet'

import gdata.docs.client

docs_client = gdata.docs.client.DocsClient()
docs_client.ClientLogin(uid, pass1, 'any')
document = gdata.docs.data.Resource(type='spreadsheet', title=name_spr)
resource = docs_client.CreateResource(document)
full_id = resource.resource_id.text # returned by gdata
gs_id = full_id[len('spreadsheet:'):]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接