List of Dictionary to xlwt

China☆狼群 提交于 2019-12-19 03:59:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!