首页 > 解决方案 > 如何使用 Python 在 GoogleSheet 中附加数据

问题描述

我有一个带有数据的谷歌表,但每天都有一个问题我必须放置数据(相同类型的数据),有人知道如何使用 python 在谷歌表中附加数据,帮助我。

我有那种类型的结果,那就是字符串

print(time, " ", todayMaxProfit, " ", todayMaxLoss, " ", pl, " ", len(
orderList), " First pair sum:- ", int(orderList[0][4]+orderList[1][4]))

"2021-08-18 15:00:00  [1451, '2021-08-18 11:07:00']  [-10203, '2021-08-18 14:45:00']  -6900  2  First pair sum:-  234"

我想最后追加数据。

在此处输入图像描述

标签: pythonpython-3.xgoogle-sheetsgoogle-sheets-api

解决方案


如何使用 Python 将值附加到 Google 电子表格。

  1. 按照快速入门进行设置。确保您完全按照所有步骤操作!您需要为您启动的每个使用 API 的项目执行此操作,因此您不妨按照此处的说明进行操作。确保在继续之前获得预期的输出!

  2. 然后,您可以修改快速入门以获取service单独的功能:

def getService():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    return build('sheets', 'v4', credentials=creds)
  1. 获得服务后,您可以调用 Sheets API。例如:
service = getService()
appendValues(service)
            
values = [
    [time, todayMaxProfit, todayMaxLoss, pl, len(orderList), int(orderList[0][4]+orderList[1][4])]
]
    
body = {'values': values}
result = service.spreadsheets().values().append(
    spreadsheetId="13rdolwpUD4h4RTuEgn1QbtgPMpJiZGMFubdh4loAfNQ", range="Sheet1!A1",
    valueInputOption="RAW", body=body).execute()

请注意,必须采用的格式values是二维列表。:

[
    [A1, B1, C1],
    [A2, B2, C2]
]

使用该append方法,只需将行按原样添加到工作表的末尾。append需要一些参数:

  • 电子表格 ID -id要附加值的电子表格的
  • range - 找到数据的粗略范围。Sheets API 将尝试评估 Sheet 中的数据并猜测最后一行的位置。通常,如果您只有一个从底部填充数据的表格A1,您可以将其保留为A1,或者C5如果您有标题或空格,则可以保留。这个想法是将 API 指向要附加到的数据集合。
  • valueInputOption - 这通常可以保留为“RAW”,它只是在传递数据时插入数据。
  • 身体,你有你的二维数据列表。

参考


推荐阅读