使用Python将字典列表转换为EXCEL

问题描述 投票:-1回答:2

我有一个词典列表:

data= [{'week': 'null', 'releasename': 'r2.0', 'tssubmiton': None, 'outstate': None,  'substate': 'null', 'recomputedon': datetime.datetime(2014, 6, 10, 0, 0), 'submittedon': datetime.datetime(2013, 6, 26, 11, 30, 9), u'state': 'new', u'month': '1306', u'item': 'null', 'engineeringaction': 'tofix'}, 
{'week': 'null', 'releasename': 'r2.0', 'tssubmiton': None, 'outstate': None, 'substate': 'null', 'recomputedon': datetime.datetime(2014, 6, 10, 0, 0), 'submittedon': datetime.datetime(2012, 10, 24, 8, 37, 48), 'state': 'new', 'month': '1301', 'item': 'null', u'engineeringaction': 'null'}]

它的时间要长得多,但这只是一个例子。如何将此dicts列表转换为Excel工作表。我不想将其转换为CSV,而是直接转换为Excel。

我使用xlwt库。

我试过这个:

wb = xlwt.Workbook()
# Creating new worksheet with the name specified
ws = wb.add_sheet(sheetName)
# Use dictionary keys as first row values(e.g. headers)
for colIdx, headerCaption in enumerate(data):
    ws.write(0, colIdx, headerCaption)
    # Use dict values as row values for corresponding columns
    for rowIdx, itemVal in enumerate(data[headerCaption]):
        ws.write(rowIdx + 1, colIdx, itemVal)
wb.save(fileName)

但我不知道如何在dicts列表上循环并将每个dict放入一个新行...

python excel xlwt
2个回答
0
投票

这应该做的伎俩:

date_format = xlwt.easyxf(num_format_str='dd/mm/yyyy')
time_format = xlwt.easyxf(num_format_str='hh:mm')
datetime_format = xlwt.easyxf(num_format_str='dd/mm/yyyy hh:mm')

def format(value):
    if value is None:
        return ("null",)
    if isinstance(value, datetime.datetime):
        return value, datetime_format
    if isinstance(value, datetime.date):
        return value, date_format
    if isinstance(value, datetime.time):
        return value, time_format
    return (value,)

# Create workbook
wb = xlwt.Workbook()
ws = wb.add_sheet("Sheet 1")

# Write header
headers = data[0].keys()
for column, header in enumerate(headers):
    ws.write(0, column, header)

# Write data
for row, row_data in enumerate(data, start=1):
    for column, key in enumerate(headers):
        ws.write(row, column, *format(row_data[key]))

# Save file
wb.save("test.xls")

您可以扩充format(...)函数以处理您需要的任何其他格式。


0
投票

我会使用列表中的第一项来编写标题:

for col,title in enumerate(data[0].keys()):
    ws.write(0,col,title)

然后填写值:

row = 0
col = 0
for d in data:
    for value in d.values():
        ws.write(row,col,value)
        col += 1
    col = 0
    row += 1
© www.soinside.com 2019 - 2024. All rights reserved.