要更新一系列单元格,请使用以下命令。
## 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)
对于我的应用程序,我希望它更新整个范围,但我试图为每个单独的单元格设置不同的值。这个例子的问题是每个单元都以相同的值结束。单独更新每个单元格效率低,耗时太长。我怎样才能有效地做到这一点?
答案 0 :(得分: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)
答案 1 :(得分: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)
答案 2 :(得分:0)
这是我想通过gspread将熊猫数据框导出到Google工作表的解决方案:
def getListIndex(nrow, ncol,row_pos, col_pos):
list_pos = row_pos*ncol + col_pos
return(list_pos)
我们可以使用此函数用数据帧df中的相应值更新列表cell_list中的正确元素。
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)
答案 3 :(得分:0)
import gspread
from gspread.models import Cell
from oauth2client.service_account import ServiceAccountCredentials
import string as string
import random
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'))
# 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)
sheet.update_cells(cells)
您可以参考这些link以获得更多详细信息。
答案 4 :(得分:0)
您可以使用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
}
])