按行填充谷歌表格,而非按单元格

2 投票
2 回答
2466 浏览
提问于 2025-04-18 15:30

我有一个电子表格,里面的值想用一个列表中的字典里的值来填充。我写了一个循环,逐个单元格更新,但速度太慢,而且经常出现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)

这个方法可以快速更新每一行,但每个单元格的值都是一样的。所以,第三个嵌套循环给每个单元格分配了相同的值。我正在绞尽脑汁想怎么才能把正确的值分配给单元格。希望能得到一些帮助。

顺便说一下,我使用表头是因为我想让谷歌电子表格中的值按照特定的顺序出现。

2 个回答

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
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)

撰写回答