Python/gspread - 如何一次更新具有不同值的多个单元格?

eco*_*is6 6 python google-app-engine google-sheets gspread

要更新一系列单元格,请使用以下命令.

## Select a range
cell_list = worksheet.range('A1:A7')

for cell in cell_list:
    cell.value = 'O_o'

## Update in batch
worksheet.update_cells(cell_list)
Run Code Online (Sandbox Code Playgroud)

对于我的应用程序,我希望它更新整个范围,但我试图为每个单独的单元格设置不同的值.这个例子的问题是每个单元都以相同的值结束.单独更新每个单元格效率低,耗时太长.我怎样才能有效地做到这一点?

ecl*_*ne6 12

您可以在包含单元格中所需的不同值的单独列表中使用枚举,并使用元组的索引部分匹配cell_list中的相应单元格.

cell_list = worksheet.range('A1:A7')
cell_values = [1,2,3,4,5,6,7]

for i, val in enumerate(cell_values):  #gives us a tuple of an index and value
    cell_list[i].value = val    #use the index on cell_list and the val from cell_values

worksheet.update_cells(cell_list)
Run Code Online (Sandbox Code Playgroud)

  • 您的示例给出了 A1:A7 的范围。只会更改第一列中的单元格。我测试过,它在我的机器上工作。它应该使 A1 = 1、A2 = 2、A3 = 3 等。如果你想要列,那么你需要 range('A1:G1') (2认同)

Pri*_*cis 5

  1. 导入模块
import gspread
from gspread.models import Cell
from oauth2client.service_account import ServiceAccountCredentials
import string as string
import random
Run Code Online (Sandbox Code Playgroud)
  1. 创建具有值的元胞数组
cells = []
cells.append(Cell(row=1, col=1, value='Row-1 -- Col-1'))
cells.append(Cell(row=1, col=2, value='Row-1 -- Col-2'))
cells.append(Cell(row=9, col=20, value='Row-9 -- Col-20'))
Run Code Online (Sandbox Code Playgroud)
  1. 找到工作表
# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('Sheet-Update-Secret.json', scope)
client = gspread.authorize(creds)
Run Code Online (Sandbox Code Playgroud)
  1. 更新单元格
sheet.update_cells(cells)
Run Code Online (Sandbox Code Playgroud)

您可以参考这些链接了解更多详情。