Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Dictionary to xlwt

I have a list of dictionary and i want to convert it to excel using xlwt. I'm new to xlwt. Can you help me? Im using it as a function to receive list of dict and convert it to excel and then return. I have this list of dict.

{'id':u'1','name':u'Jeff'}

 {'id':u'2','name':'Carlo'}
like image 568
Nethan Avatar asked Dec 26 '22 15:12

Nethan


2 Answers

If somebody need version with HEADERS:

import xlwt

w = xlwt.Workbook()
ws = w.add_sheet('sheet1')

columns = list(data[0].keys())

# write headers in row 0
for j, col in enumerate(columns):
    ws.write(0, j, col)

# write columns, start from row 1
for i, row in enumerate(data, 1):
    for j, col in enumerate(columns):
        ws.write(i, j, row[col])

w.save('data.xls')
like image 54
andilabs Avatar answered Jan 02 '23 12:01

andilabs


Make a worksheet. Then use Worksheet.write to fill a cell.

data = [
    {'id':u'1','name':u'Jeff'},
    {'id':u'2','name':'Carlo'},
]

import xlwt

w = xlwt.Workbook()
ws = w.add_sheet('sheet1')

columns = list(data[0].keys()) # list() is not need in Python 2.x
for i, row in enumerate(data):
    for j, col in enumerate(columns):
        ws.write(i, j, row[col])

w.save('data.xls')
like image 27
falsetru Avatar answered Jan 02 '23 12:01

falsetru