我有一些数据想要导出到 Excel 电子表格中。数据包含元素数量可变的嵌套字典。
看起来像这样
[{ "12345" :
{ "cup" : "123456789",
"spoon" : "234567891",
}
},
{ "23456" :
{ "plate" : "345678912",
}
}
]
我想将这些数据导出到 Excel 电子表格中,如下所示:
我的数据更复杂,但我想如果我了解如何完成此操作,我可以自己应用它。
所以我正在考虑使用 xlsxwriter python 模块,但我必须循环数据来创建单元格。 然后我想起 Pandas 有一种简单的方法可以在数据框中导入此类数据,并且有很好的 Excel 导出功能。
但我现在不知道 Pandas 是否支持合并单元格之类的东西。
在这种情况下您建议使用什么?
我自己还没有尝试过,但像 xlsxWriter 这样的东西可能会有用。这是您所要求的功能的示例。
这只需使用 Xlsxwriter 即可完成。
这是一个例子,我在列表中包含了一些额外的数据以供展示;
import xlsxwriter
data_list = [
{"12345":
{"cup": "123456789",
"spoon": "234567891",
}
},
{"23456":
{"plate": "345678912",
}
},
{"11111":
{"knife": "12121212",
"fork": "23232323",
"spoon": "34343434"
}
},
{"22222":
{"cup": "56565656",
"saucer": "67676767"
}
}
]
### New workbook and sheet
wb = xlsxwriter.Workbook('xlsxwriter_merge_example.xlsx')
ws = wb.add_worksheet()
### Basic cell formatting
cell_format = wb.add_format({"align": "center", "valign": "vcenter"})
### Insert row 1 Header text and merge
ws.write(0, 0, 'Order', cell_format)
ws.merge_range("B1:C1", "Item", cell_format)
### Loop through the List to extract the dictionaries and write to the rows
### after row 1.
### If there is more than one entry in the 'item' section then merge the 'Order' cell to that range.
row_index = 1
for row_data in data_list:
for col_index, (cell_key, cell_value) in enumerate(row_data.items()):
if len(cell_value) >= 2:
ws.merge_range(row_index,
col_index,
(row_index + len(cell_value)) - 1,
col_index,
cell_key,
cell_format)
else:
ws.write(row_index, col_index, cell_key, cell_format)
for item_key, item_value in cell_value.items():
ws.write(row_index, col_index + 1, item_key)
ws.write(row_index, col_index + 2, item_value)
row_index += 1
wb.close()