繁体   English   中英

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

[英]Python/gspread - how can I update multiple cells with DIFFERENT VALUES at once?

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

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

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

您可以在包含单元格中所需不同值的单独列表上使用枚举,并使用元组的索引部分匹配 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)
  1. 导入模块
import gspread
from gspread.models 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)

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

假设有一个表头行,如下:

Name  | Weight
------+-------
Apple | 56
Pear  | 23
Leaf  | 88

那么,以下应该是不言自明的

cell_list = []

# get the headers from row #1
headers = worksheet.row_values(1)
# find the column "Weight", we will remember this column #
colToUpdate = headers.index('Weight')

# task 1 of 2
cellLookup = worksheet.find('Leaf')
# get the cell to be updated
cellToUpdate = worksheet.cell(cellLookup.row, colToUpdate)
# update the cell's value
cellToUpdate.value = 77
# put it in the queue
cell_list.append(cellToUpdate)

# task 2 of 2
cellLookup = worksheet.find('Pear')
# get the cell to be updated
cellToUpdate = worksheet.cell(cellLookup.row, colToUpdate)
# update the cell's value
cellToUpdate.value = 28
# put it in the queue
cell_list.append(cellToUpdate)

# now, do it
worksheet.update_cells(cell_list)

如果您想使用 gspread 将 Pandas 数据框导出到 Google 表格,这是我的解决方案:

  • 我们无法使用 [row, col] 符号直观地使用数据框中的值访问和替换 cell_list 中的元素。
  • 但是,元素存储在“cell_list”中,按“行”顺序存储。 相对顺序取决于数据框中的列数。 元素 (0,0) => 0,5x5 数据帧中的元素 (3,2) 为 17。
    • 我们可以构造一个函数,将数据框中的 [row, col] 值映射到它在列表中的位置:
def getListIndex(nrow, ncol,row_pos, col_pos):
    list_pos = row_pos*ncol + col_pos
    return(list_pos)

我们可以使用此函数来更新列表中正确的元素 cell_list,以及数据帧中的相应值 df。

count_row = df.shape[0]
count_col = df.shape[1]

# note this outputs data from the 1st row
cell_list = worksheet.range(1,1,count_row,count_col)

for row in range(0,count_row):
    for col in range(0,count_col):
        list_index = getListIndex(count_row, count_col, row, col)
        cell_list[list_index].value = df.iloc[row,col]

我们可以将列表的结果 cell_list 输出到我们的工作表。

worksheet.update_cells(cell_list)

您可以使用 batch_update() 或 update()。 https://github.com/burnash/gspread

worksheet.batch_update([
            {
                'range': 'A1:J1', # head
                'values': [['a', 'b', 'c']],
            },
            {
                'range': 'A2', # values
                'values': df_array 
            }
        ])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM