返回顶部
扶摇直上九万里,展翅高飞岂可待。

python菜鸟学习 : 16 pymongo和openpyxl的联合使用

# -*- coding: utf-8 -*-

import pymongo, openpyxl, time
# pymongo

#条件删选mongodb数据
def mongodb_expoter(db_name, col_name, **kwargs):
mongodb_string = "mongodb://192.168.126.128:27018"
mycenlit = pymongo.MongoClient(mongodb_string)
mydb = mycenlit[db_name]
mycol = mydb[col_name]
mycenlit.close()
# 将**kwargs转化成字典传入筛选条件中
data01 = mycol.find(dict(**kwargs))
mycenlit.close()
return data01

#将数据导出到excel中
def writeExcel(db_name, col_name, **kwargs):
nowtime = time.strftime('%Y%m%d%H%M%S')
mydata = mongodb_expoter(db_name, col_name, **kwargs)
webook = openpyxl.Workbook()
webook.create_sheet(col_name)
row1 = 1
for i in mydata:
col1 = 1
for key, value in dict(i).items():
webook[col_name].cell(row1, col1, str(key) + ":" + str(value))
col1 += 1
row1 += 1
webook.save("{col_name}_{time}.xlsx".format(time=nowtime, col_name=col_name))




posted @ 2022-11-03 17:56  鲤鱼洲畔  阅读(26)  评论(0编辑  收藏  举报