簡體   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