如何使用Python在GoogleSheet中追加数据

2024-10-02 12:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有数据的google工作表,但它每天都有一个问题,我必须输入数据(相同类型的数据),有人知道如何使用python在google工作表中添加数据,请帮助我

我有那个类型的结果,它是字符串

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"

最后我想添加数据

enter image description here


Tags: 数据字符串类型lentimegoogleintfirst
2条回答

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

  1. 按照quickstart进行设置。确保您完全按照所有步骤操作!对于开始使用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有几个参数:

  • spreadsheetId—要向其添加值的电子表格的id
  • 范围-找到数据的大致范围。Sheets API将尝试评估工作表中的数据,并猜测最后一行在哪里。通常,如果一个表从A1到底部填充了数据,则可以将其保留为A1,或者如果有标题或空格,可以保留为C5。其思想是将API指向要附加到的数据集合
  • valueInputOption-这通常可以保留为“原始”,在传递数据时只插入数据
  • 主体,这里有二维数据列表

参考文献

您好,您可以尝试pygsheets,它工作良好,易于使用

import pygsheets
gc = pygsheets.authorize(service_file='creds.json')
sh = gc.open('sheetname')  # Open GoogleSheet
worksheet1 = sh.worksheet('title', 'worksheetname')  # choose worksheet to work with
worksheed1.append_table(values=["Date", "blah", 1, '\'+', "ect"])  # append row to worksheet

相关问题 更多 >

    热门问题