【问题标题】:Can I update cells without getting their current values first using gspread我可以在不先使用 gspread 获取当前值的情况下更新单元格吗
【发布时间】:2019-09-17 20:52:16
【问题描述】:

我有一个谷歌表格,我正在根据我在 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)```

【问题讨论】:

    标签: python google-sheets-api gspread


    【解决方案1】:

    您可以使用 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)
    
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      相关资源
      最近更新 更多