gspread import_csv file_id 参数是什么?

What is the gspread import_csv file_id parameter?

我正在尝试使用 gspread Python package 从命令行将 CSV 数据导入 Google sheet。

Using this guide,我一切正常,并且能够读取和写入单元格。

但是逐一更新单元格太慢了,所以我现在尝试使用 import_csv() 方法。 The docs say:

import_csv(file_id, data) Imports data into the first page of the spreadsheet.

Parameters: data – A CSV string of data.

file_id 这里没有描述,我想不出应该是什么。其他一些方法也使用 file_id 并且对于它们来说它被描述为:

file_id – a spreadsheet ID (aka file ID.)

我不确定在哪里可以找到 spreadsheet ID,无论我尝试什么,我都会遇到权限错误。由于我能够使用 update_cell(),如上所述,我认为我的权限工作正常但我使用了错误的 file_id.

这是简化的代码:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
sheet = client.open("SheetTitle").sheet1

# This works fine, so I think permissions etc are all set up correctly
sheet.update_cell(1, 1, 'Foo')

# Now try importing CSV data from a string
csv="""2016, 2017
1,2
3,4
"""

# Does not work
client.import_csv(sheet, csv);

# Using the spreadsheet_id in the URL as described here https://developers.google.com/sheets/api/guides/concepts#spreadsheet_id
client.import_csv('11x...', csv);

# Using the "#gid=0" value in the query string in the browser when looking at this sheet
client.import_csv(0, csv);

这是我得到的错误,无论我尝试以上哪一个:

Traceback (most recent call last):
  File "./simple.py", line 22, in <module>
    client.import_csv(sheet, csv);
  File "/Library/Python/2.7/site-packages/gspread/client.py", line 297, in import_csv
    headers=headers
  File "/Library/Python/2.7/site-packages/gspread/httpsession.py", line 82, in put
    return self.request('PUT', url, params=params, data=data, **kwargs)
  File "/Library/Python/2.7/site-packages/gspread/httpsession.py", line 69, in request
    response.status_code, response.content))
gspread.exceptions.RequestError: (403, '403: {\n "error": {\n  "errors": [\n   {\n    "domain": "global",\n    "reason": "insufficientPermissions",\n    "message": "Insufficient Permission"\n   }\n  ],\n  "code": 403,\n  "message": "Insufficient Permission"\n }\n}\n')

https://www.googleapis.com/auth/drive 添加到您的 scope 变量,它将起作用:

scope=[
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]

你需要范围内的 Google 驱动器的原因是因为 import_csv 实际上向 Google 驱动器 API 调用而不是 [=20] 发出 HTTP 请求=] 张 API.

遇到这个问题时遇到了我自己的问题。虽然已经被作者接受,但让我分享我的 2 美分。 首先:是的,你需要在你的范围内有正确的路径。但要澄清什么是 id:

来自 gspread API 参考: http://gspread.readthedocs.io/en/latest/

模型电子表格有一个 id 字段。这就是 import_csv(file_id, data) 函数应该使用的内容。 请注意,有 3 种不同的模型: - 电子表格 - 工作表 - 单元格。

从您的示例代码中,您实际上获得了工作表对象。

sheet = client.open("SheetTitle").sheet1

它也有一个 id,但我很确定这行不通。

您需要获取电子表格对象并使用其 ID。

sheet = client.open("SheetTitle") client.import_csv(sheet.id, csv);

您可以通过打印来验证该id是否与您直接输入的id相同 print(sheet.id)