eco*_*is6 6 python google-app-engine google-sheets 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)
Run Code Online (Sandbox Code Playgroud)
对于我的应用程序,我希望它更新整个范围,但我试图为每个单独的单元格设置不同的值.这个例子的问题是每个单元都以相同的值结束.单独更新每个单元格效率低,耗时太长.我怎样才能有效地做到这一点?
ecl*_*ne6 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)
Run Code Online (Sandbox Code Playgroud)
import gspread
from gspread.models import Cell
from oauth2client.service_account import ServiceAccountCredentials
import string as string
import random
Run Code Online (Sandbox Code Playgroud)
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'))
Run Code Online (Sandbox Code Playgroud)
# 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)
Run Code Online (Sandbox Code Playgroud)
sheet.update_cells(cells)
Run Code Online (Sandbox Code Playgroud)
您可以参考这些链接了解更多详情。