【问题标题】:Python/gspread - how can I update multiple cells with DIFFERENT VALUES at once?Python/gspread - 如何一次更新具有不同值的多个单元格?
【发布时间】:2013-05-21 16:44:15
【问题描述】:

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

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

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

【问题讨论】:

    标签: python google-app-engine google-sheets gspread


    【解决方案1】:

    您可以在包含单元格中所需不同值的单独列表上使用枚举,并使用元组的索引部分来匹配 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”,其余为“none”
    • 您的示例给出了 A1:A7 的范围。只有第一列中的单元格会被更改。我测试过,它可以在我的机器上运行。它应该使 A1 = 1、A2 = 2、A3 = 3 等。如果你想要列,那么你需要 range('A1:G1')
    • 我的错误,我修改了它以将数据输入列而不是行。我还需要做其他调整吗?
    • 唯一棘手的一点是您需要确保 cell_list 的长度与 cell_values 列表的长度相同。如果它们的长度不同,您将收到“索引超出范围”错误。否则,此方法应按预期工作。
    • 没有看到你现在所说的代码,我无法想象发生了什么。
    【解决方案2】:
    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)
    

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

    【讨论】:

    • Cell 现在导入如下: from gspread.cell import Cell
    【解决方案3】:

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

    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)
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        如果您想使用 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)
        

        【讨论】:

        • 非常有用!非常感谢您在 pandas 和 gspread 之间建立这种联系。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        相关资源
        最近更新 更多