signed

QiShunwang

“诚信为本、客户至上”

PYTHON 数据库导出到EXCEL表格

2021/6/3 17:58:14   来源:
# -*- coding: utf-8 -*-
from openpyxl import Workbook
import pymongo
# 读取mongoDB数据库相应的表,每条数据取出数个字段存入一个dict,再将所有的dict存入一个list
def read_mongoDB():
    # 连接mongoDB数据库,读取 db 库 table 表中的数据
    client = pymongo.MongoClient('39.106.168.232', 27017)
    db = client['zsbao_mongodb']
    db.authenticate("zsbao_user", "zsbao_dbA_695M")
    table = db['zsbao_member']

    # 创建list用于存储从mongoDB中读取到的数据
    mongo_data_list = []
    # 从table中读取的数据为整个documents内容
    documents = table.find()
    # 遍历 documents 表中的每一个document
    for document in documents:
        # 创建dict用于存储各条数据的各个字段名称及内容

        mongo_data_dict = {}
        id = document.get("_id")
        uname = document.get("uname")
        phone = document.get("phone")
        # 将查询到的的数据字段内容以更新添加的方式添加到每个dict中
        if phone != "":
            mongo_data_dict.update({"uname": uname})
            mongo_data_dict.update({"phone": phone})
            mongo_data_dict.update({"id": id})
        else:
            pass
        print("mongo_data_dict:", mongo_data_dict)
        mongo_data_list.append(mongo_data_dict)
    return mongo_data_list


# 保存至本地excel表格
def save_to_excel(mongoDB_data):
    outwb = Workbook()
    outws = outwb.worksheets[0]
    # 遍历外层列表
    for new_dict in mongoDB_data:
        a_list = []
        # 遍历内层每一个字典dict,把dict每一个值存入list
        for item in new_dict.values():
            a_list.append(item)
        # sheet直接append list即可
        outws.append(a_list)

    outwb.save(r'C:\Users\zhenshibao\Desktop\用户数据.xlsx')
    print('数据存入excel成功')


def main():
    mongoDB_data = read_mongoDB()
    save_to_excel(mongoDB_data)


if __name__ == '__main__':
    main()