使用 gspread 或 googleapiclient 将行追加到 Google 表格

use*_*457 6 google-api google-sheets python-3.x pandas gspread

任务:我有一个数据框,我想将该数据附加到 Google 表格中。该工作表具有与 DF 完全相同的列,并且具有我不想覆盖的现有数据,但只需使用 DF 中的值在工作表末尾添加行。

到目前为止尝试过:

  1. 我使用以下代码遵循了 gspread 的文档:
    import json
    df2.to_json(orient = 'columns')
    values = df2.to_json(orient = 'columns')
    wks.append_row (values, value_input_option='USER_ENTERED')
Run Code Online (Sandbox Code Playgroud)

结果:APIError:{“错误”:{“代码”:400,“消息”:“'data.values [0]'处的值无效(type.googleapis.com/google.protobuf.ListValue),

  1. 我遵循了 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)
Run Code Online (Sandbox Code Playgroud)

结果:AttributeError:“ServiceAccountCredentials”对象没有属性“request”

问题:这些解决方案中的任何一个都是正确的方法吗?我该如何修复错误?或者有一个完全不同的更容易的选择吗?

谢谢你!

Tan*_*ike 4

  • 您想要将 的值附加df2到 Google 电子表格。
  • 您希望通过服务帐户使用 gspread 来实现此目的。
  • 您已经能够通过服务帐户使用 Sheets API 获取和输入 Google 电子表格的值。

如果我的理解是正确的,这个答案怎么样?请将此视为几个可能答案中的一个。

修改要点:

  • 在你的情况下,使用df2.values.tolist()而不是怎么样 df2.to_json(orient = 'columns')?这样,值就被转换为二维数组。
  • 当 的值有多行时df2,我建议使用 的方法values_append代替append_row。因为append_row用于一维数组。这种情况下,当使用多行的值时,append_row需要在循环中使用。当values_append用于多行的值时,可以通过一次 API 调用来放置这些值。

修改后的脚本:

当您的脚本修改时,请修改如下。

spreadsheetId = '###'  # Please set the Spreadsheet ID.
sheetName = 'Sheet1'  # Please set the sheet name.

client = gspread.authorize(credentials)
sh = client.open_by_key(spreadsheetId)
df2 = pd.DataFrame({'col1': ['a1', 'a2', 'a3'], 'col2': ['b1', 'b2', 'b3']})  # This is a sample value.
values = df2.values.tolist()
sh.values_append(sheetName, {'valueInputOption': 'USER_ENTERED'}, {'values': values})
Run Code Online (Sandbox Code Playgroud)
  • df2 = pd.DataFrame({'col1': ['a1', 'a2', 'a3'], 'col2': ['b1', 'b2', 'b3']})是一个样本值。使用此功能时,值将附加到工作表中。

参考:

如果我误解了你的问题并且这不是你想要的方向,我很抱歉。