Python gspread - 循环行 - 使用同一行中其他两个单元格的总和或差值更新单元格

问题描述 投票:0回答:1

我想填充一个谷歌电子表格,以便对于某一列的每一行,for循环插入同一行的其他两个单元格之间的总和或差,但我一生都无法弄清楚。抱歉,我是编程新手。

我的代码如下所示(我省略了电子表格中的一些列):

import gspread
from google.oauth2.service_account import Credentials

scopes = ["https://www.googleapis.com/auth/spreadsheets"]
creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)
client = gspread.authorize(creds)

sheet_id = "url"
workbook = client.open_by_key(sheet_id)

worksheet_list = map(lambda x: x.title, workbook.worksheets())
new_worksheet_name = "template"

# check if new sheet exists already
if new_worksheet_name in worksheet_list:
    sheet = workbook.worksheet(new_worksheet_name)
else:
    sheet = workbook.add_worksheet(new_worksheet_name, rows=100, cols=30)

values = [
    ["Starting funds", "Bet", "Funds after bet],
]

sheet.clear()

sheet.update(values, f"A1:Z{len(values)}")

sheet.update_acell("A2", 250)
sheet.update_acell("B2", 10)

我希望单元格 C2 显示 A2 和 B2 的和(或差),单元格 C3 显示 A3 和 B3 的和(或差),依此类推

对于细胞之间的差异,我尝试过:

rows = sheet.get_all_values()
for row in rows[1:]:
    sheet.update_cell(row, 3, "=A:A-B:B")

但我得到以下回溯:

  File "path", line 72, in <module>
    sheet.update_cell(row, 3, "=A:A-B:B")
  File "path\.venv\Lib\site-packages\gspread\worksheet.py", line 751, in update_cell
    range_name = absolute_range_name(self.title, rowcol_to_a1(row, col))
                                                 ^^^^^^^^^^^^^^^^^^^^^^
  File "path\.venv\Lib\site-packages\gspread\utils.py", line 306, in rowcol_to_a1
    if row < 1 or col < 1:
       ^^^^^^^
TypeError: '<' not supported between instances of 'list' and 'int'type here
python google-sheets gspread
1个回答
0
投票

发生错误是因为 update_cell 方法需要两个整数作为其前两个参数:行号和列号。但是,您将一个列表(行,即电子表格中的一行)和一个整数(3 表示列号)传递给 update_cell。

for i, row in enumerate(rows[1:], start=2):
    formula = f"=A{i}-B{i}"
    sheet.update_cell(i, 3, formula)
© www.soinside.com 2019 - 2024. All rights reserved.