【发布时间】:2020-01-22 13:27:06
【问题描述】:
任务:我有一个数据框,我想将该数据附加到 Google 表格中。该工作表具有与 DF 完全相同的列,并且具有我不想覆盖的现有数据,但只需使用来自 DF 的值在工作表末尾添加行。
到目前为止尝试过:
- 我使用以下代码遵循了有关 gspread 的文档:
import json
df2.to_json(orient = 'columns')
values = df2.to_json(orient = 'columns')
wks.append_row (values, value_input_option='USER_ENTERED')
结果:API错误:{ “错误”: { “代码”:400, "message": "'data.values[0]' (type.googleapis.com/google.protobuf.ListValue) 处的值无效,
- 我已经按照 Google 的 API 参考文档:https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append
!pip install --upgrade google-api-python-client
from pprint import pprint
from googleapiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/spreadsheets']
credentials = ServiceAccountCredentials.from_json_keyfile_name('NAME.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open("SHEETNAME").sheet1
service = discovery.build(wks,'v1', credentials)
spreadsheet_id = 'MYID'
value_input_option = INSERT_ROWS
values = df2.to_json(orient = 'columns')
insert_data_option = values
request = service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range_, valueInputOption=value_input_option, insertDataOption=insert_data_option, body=value_range_body)
response = request.execute()
pprint(response)
结果:AttributeError:“ServiceAccountCredentials”对象没有属性“request”
问题:这些解决方案中的任何一个都是正确的方法吗?我该如何解决这些错误?还是有更简单的完全不同的选择?
谢谢!
【问题讨论】:
-
您能分享您在 (2) 中使用的代码吗?是否要使用服务帐户附加行?
-
是的,我已经设置了一个服务帐户。现在共享有问题的代码。谢谢!
标签: python-3.x pandas google-sheets google-api gspread