问题
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'}
回答1:
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')
回答2:
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')
来源:https://stackoverflow.com/questions/21085782/list-of-dictionary-to-xlwt