문제

목록 내의 사전에서 값을 채우고 싶은 값이있는 스프레드 시트가 있습니다. 셀별로 셀을 업데이트하는 루프를 썼지 만 너무 느리고 gspread.httpsession.htTtperrror를 자주 얻을 수 있습니다. 행으로 행을 업데이트하기 위해 루프를 작성하려고합니다. 그게 내가 가진 것 :

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

이 하나의 행은 각 행을 빠르지 만 동일한 값으로 업데이트됩니다. 따라서 세 번째 중첩 된 루프는 각 셀에 동일한 값을 할당합니다. 나는 셀에 오른쪽 값을 할당하는 방법을 알아 내려고 노력하고 있습니다. 감사하도록 도와주세요.

p.s. Google 스프레드 시트의 값이 표시되어야하는 특정 순서를 원하기 때문에 헤더를 사용하고 있습니다.

도움이 되었습니까?

해결책

다음 코드는 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