需求:针对mongo数据库的数据进行提取,因为mongo数据库的字段是可伸缩的,所以导致没有值的key不会出现,针对提取的该数据的嵌套字典做处理,如下所示,给了一个data的示例数据
import openpyxl
class OperationExcel(object):
"""处理Excel数据,并且写入
"""
def __init__(self, sheet):
"""
根据嵌套字典获取Excel的表头
:param sheet: 定义一个sheet的名称
"""
self.wb = openpyxl.Workbook()
self.ws = self.wb.create_sheet(index=0, title=sheet)
def get_title(self, data):
"""
:param data: 传入json数据的嵌套字典
:return: 返回所有字典的标题(keys)
"""
title_list = []
for dic in data:
for key in dic:
if key not in title_list:
title_list.append(key)
return title_list
def handle_data(self, title_list, data, filename):
"""
:param data: 调用get_title返回的标题列表
:param data: 传入json数据的嵌套字典
:return: 返回所有字典的标题(keys)
"""
# 1. 把列表的标题插入Excel的第一行
first_row = 1
for header in title_list:
col = title_list.index(header)
self.ws.cell(first_row, col + 1, header)
# 2. 把所有的值,根据标题去筛选,插入excel
row = 2
for player in data:
for _key, _value in player.items():
col = title_list.index(_key)
self.ws.cell(row, col + 1, _value)
row += 1 # enter the next row
self.wb.save(filename)
self.wb.close()
if __name__ == '__main__':
filename = "上海数据.xlsx"
sheet = "数据清洗"
data = [{'欢迎': 4, "马上": 3, "登录": "成功"}, {'欢迎': 5, "马上": 7, "退出": "成功"}, {'欢迎': 9, "马上": 8, "注册": "失败"}]
A = OperationExcel(sheet)
title_list = A.get_title(data)
# 清洗数据,写入Excel
A.handle_data(title_list=title_list,
data=data,
filename=filename)
1.从mongo提取数据,返回字典格式可以参考我之前的文章: