2

我有一个电子表格,我想用列表中字典的值填充其值。我编写了一个逐个单元格更新的 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)

它所做的是找到与字典列表中的键对应的标题并更新其下的单元格。下一次迭代该行增加一,因此它更新同一列中的单元格,但下一行。这太慢了,我想逐行更新。我的尝试:

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 循环为每个单元格分配相同的值。我正在努力弄清楚如何为单元格分配正确的值。帮助表示赞赏。

PS顺便说一句,我使用标题是因为我想要谷歌电子表格中的值应该出现的特定顺序。

4

2 回答 2

4

以下代码类似于 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)
于 2016-06-01T12:27:31.267 回答
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
于 2014-08-01T17:55:39.967 回答