我有一个电子表格,其值我想用列表中的字典值填充。我编写了一个逐个单元更新的for循环,但它太慢了,我经常得到gspread.httpsession.HTTPError。我试图写一个循环来逐行更新。多数民众赞成的东西:
lstdic=[
{'Amount': 583.33, 'Notes': '', 'Name': 'Jone', 'isTrue': False,},
{'Amount': 58.4, 'Notes': '', 'Name': 'Kit', 'isTrue': False,},
{'Amount': 1083.27, 'Notes': 'Nothing', 'Name': 'Jordan', 'isTrue': True,}
]
这是我的逐个细胞循环:
headers = wks.row_values(1)
for k in range(len(lstdic)):
for key in headers:
cell = wks.find(key)
cell_value = lstdic[k][key]
wks.update_cell(cell.row + 1 + k, cell.col, cell_value)
它的作用是找到一个与字典列表中的键对应的标题,并更新其下的单元格。下一次迭代该行增加1,因此它更新相同列中的单元格,但下一行。这太慢了,我想按行更新。我的尝试:
headers = wks.row_values(1)
row=2
for k in range(len(lsdic)):
cell_list=wks.range('B%s:AA%s' % (row,row))
for key in headers:
for cell in cell_list:
cell.value = lsdic[k][key]
row+=1
wks.update_cells(cell_list)
这一行快速更新每一行,但具有相同的值。因此,第三个嵌套的for循环为每个单元格分配相同的值。我正试图弄清楚如何为细胞分配正确的值。帮助赞赏。
P.S。顺便说一句,我使用标题,因为我想要一个特定的订单,其中应该出现谷歌电子表格中的值。
答案 0 :(得分:3)
以下代码与Koba的答案类似,但是一次写入整张表而不是每行。这甚至更快:
# sheet_data is a list of lists representing a matrix of data, headers being the first row.
#first make sure the worksheet is the right size
worksheet.resize(len(sheet_data), len(sheet_data[0]))
cell_matrix = []
rownumber = 1
for row in sheet_data:
# max 24 table width, otherwise a two character selection should be used, I didn't need this.
cellrange = 'A{row}:{letter}{row}'.format(row=rownumber, letter=chr(len(row) + ord('a') - 1))
# get the row from the worksheet
cell_list = worksheet.range(cellrange)
columnnumber = 0
for cell in row:
cell_list[columnnumber].value = row[columnnumber]
columnnumber += 1
# add the cell_list, which represents all cells in a row to the full matrix
cell_matrix = cell_matrix + cell_list
rownumber += 1
# output the full matrix all at once to the worksheet.
worksheet.update_cells(cell_matrix)
答案 1 :(得分:2)
我最后编写了以下循环,按行快速填充电子表格。
headers = wks.row_values(1)
row = 2 # start from the second row because the first row are headers
for k in range(len(lstdic)):
values=[]
cell_list=wks.range('B%s:AB%s' % (row,row)) # make sure your row range equals the length of the values list
for key in headers:
values.append(lstdic[k][key])
for i in range(len(cell_list)):
cell_list[i].value = values[i]
wks.update_cells(cell_list)
print "Updating row " + str(k+2) + '/' + str(len(lstdic) + 1)
row += 1