l3xand3r
l3xand3r

Reputation: 11

Export python loop results to corresponding columns in Excel using xlsxwriter

I have a loop which retrieves two lists of values from some json. I would like to export each one of the values list (1000 results each one) with its header to Exscel. All values are available when I'm printing the results, but Excel sheet contains only header and a single row. Perhaps, I'm missing some loop to add. Any help is appreciated!

list = x.json() 
    
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

for item in list:
    item1 = value1['valueID1']
    item2 = value2['valueID2']

    data = {"item1": [item1],"item2": [item2]}

    col_num = 0
    for key, value in data.items():
        worksheet.write(0, col_num, key)
        worksheet.write_column(1, col_num, value)
        col_num += 1
    workbook.close()

Upvotes: 1

Views: 267

Answers (1)

Python Bang
Python Bang

Reputation: 482

You need to increment the row value as well.

list = x.json() 
    
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

for item in list:
    item1 = value1['valueID1']
    item2 = value2['valueID2']

    data = {"item1": [item1],"item2": [item2]}

    col_num = 0
    row_num = 0

    for key, value in data.items():
        worksheet.write(row_num , col_num, key)
        worksheet.write_column(row_num , col_num, value)
        col_num += 1
    row_num=row_num+1
workbook.close()

Upvotes: 1

Related Questions