Python/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)

对于我的应用程序,我希望它更新整个范围,但我试图为每个单独的单元格设置不同的值。此示例的问题在于每个单元格最终都具有相同的值。单独更新每个单元格效率低下并且花费的时间太长。我怎样才能有效地做到这一点?

原文由 ecollis6 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 657
2 个回答

您可以在包含单元格中所需的不同值的单独列表上使用枚举,并使用元组的索引部分来匹配 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)

原文由 ecline6 发布,翻译遵循 CC BY-SA 3.0 许可协议

  1. 导入模块
import gspread
from gspread.cell import Cell
from oauth2client.service_account import ServiceAccountCredentials
import string as string
import random

  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'))

  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)

  1. 更新单元格
sheet.update_cells(cells)

你可以参考 我的博客文章 了解更多细节。

原文由 Prince Francis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题