python - 我可以在不先使用 gspread 获取当前值的情况下更新单元格吗

标签 python google-sheets-api gspread

我有一个 google 表格,我正在根据我在 python 脚本中进行的一些 API 调用的结果插入/更新它的值。

按照 gspread 文档,我目前正在从工作表中获取范围,然后更新值,然后将其写回。

但我不关心工作表中的值,我宁愿盲目地写入它 - 节省我宝贵的 API 读取配额。

有没有一种方法可以在不先读取单元格的情况下写入单元格?

我在谷歌上搜索过任何遇到同样问题的人,但我找不到任何地方告诉我如何做到这一点(或者即使我完全可以)

当前代码:

(rowData 是我之前在 python 脚本中收集的数据,我现在要写入 gsheet)

try:
        rowToUpdate = sheet.range("A"+str(index)+":Q"+str(index))
except Exception as e:
        print("Couldn't fetch rowToUpdate, error message was: ")
        print(repr(e))

try:
        for cell, value in zip(rowToUpdate, rowData):
            cell.value = value
        sheet.update_cells(rowToUpdate)

理想情况下我会做类似的事情:

    try:
        for cell, value in zip(rowToUpdate, rowData):
            cell.value = value
        sheet.update_cells(rowToUpdate)```

最佳答案

您可以使用 Sheetfu 库(我是作者):https://github.com/socialpoint-labs/sheetfu

下面的代码只是设置值,而不是首先实际获取值:

from sheetfu import SpreadsheetApp as sa

spreadsheet = sa('path/to/secret.json').open_by_id('<insert spreadsheet id here>')
sheet = spreadsheet.get_sheet_by_name('<insert the sheet name here>')

# make sure your data is already in a 2D matrix form
input_data = [[1,2], [3,4]]

data_range = sheet.get_range(
    row=1, 
    column=1, 
    number_of_row=len(input_data), 
    number_of_column=len(input_data[0])
)

data_range.set_values(input_data)

此代码不会查询工作表并获取当前值。它只会使用您的数据设置值。

关于python - 我可以在不先使用 gspread 获取当前值的情况下更新单元格吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55899829/

相关文章:

python-2.7 - gspread 输入前面有单引号

android - 为什么这个 shell 脚本将自己称为 python 脚本?

python - Django表单修改HTML标签

python - 从 Google 表格电子表格调用 python 脚本的好方法是什么?

google-apps-script - Google表格,用于在一个单元格中设置多个超链接的脚本

google-apps-script - 从脚本分配传入 Google 电子表格脚本中的参数

python - 如何在 gspread 中预定义行数和列数

google-apps-script - 使用 gspread 写入时出现 Google Sheets API 权限错误

python - 模块未找到错误: No module named 'pandas' in GitHub Actions

python - Matplotlib 不在图例中显示补丁的影线