参考:https://www.cnblogs.com/similarface/p/5608987.html
依赖于python2.7
模块:xlwt,pymongo
实践代码
# -*- coding:utf-8 -*-
# 参考:https://www.cnblogs.com/similarface/p/5608987.html
import xlwt
import sys
from pymongo import MongoClient
reload(sys) # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法,我们需要重新载入
sys.setdefaultencoding('utf-8')
client = MongoClient()
client = MongoClient('10.10.*.*', 20000)
# 连接mongodb数据库
client = MongoClient('mongodb://10.10.*.*:20000/')
# 指定数据库名称
bill = client.bill
# 获取非系统的集合
bill.collection_names(include_system_collections=False)
# 获取集合名
bill = bill.bill
def find(param):
list = []
cursor = bill.find().limit(100)
for e in cursor:
line = []
# print "%s,%s,%s,%s,%s,%s,%s" % ( e['bill_time'], e['mobile'], e['content'], e['msgseq'], e['msgcnt'], e['deliverd'], e['report_text'])
line.append(e.get('bill_time', ''))
line.append(e.get('mobile', ''))
line.append(str(e.get('content', '')))
line.append(e.get('msgseq', ''))
line.append(e.get('msgcnt', ''))
line.append(e.get('deliverd', ''))
line.append(e.get('report_text', ''))
list.append(line)
print line
# print "%s,%s,%s,%s,%s,%s,%s"%(cursor['bill_time'],cursor['mobile'],cursor['content'],cursor['msgseq'],cursor['msgcnt'],cursor['deliverd'],cursor['report_text'])
return list
def create_xls(file_path, list):
workbook = xlwt.Workbook(encoding='utf-8') # 注意Workbook的开头W要大写
sheet1 = workbook.add_sheet('sheet1', cell_overwrite_ok=True)
# 向sheet页中写入数据
for i, j in enumerate(list):
if (i % 10000 == 0):
print("执行到第%s行" % (i + 1))
for s, k in enumerate(j):
sheet1.write(i, s, str(k))
file_path = file_path.replace('\\', '/')
workbook.save(file_path)
print('创建excel文件完成!')
return file_path
if __name__ == '__main__':
list = find({"bill_time": "20171212", "mobile": "18888888888"})
create_xls("/Users/temp/out.xls", list=list)