我有一个电子表格,其值我想要用列表中的字典中的值填充。我写了一个用于更新单元格按单元格的循环,但它太慢,我会得到gspread.htptpsession.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循环的第三个嵌套为每个单元分配相同的值。我正在打破我的脑袋试图弄清楚如何为小区分配正确的值。帮助感谢。

p.s。顺便说一下,我使用标题,因为我想要一定的顺序,其中应该出现在谷歌电子表格中的值。

有帮助吗?

解决方案

以下代码类似于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)
.

其他提示

我最终编写了以下循环,通过行填充了一行令人惊讶。

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
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top