python操作MySQL数据库并将数据写入excel

#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
方法:通过pymsql模块连接mysql数据库,然后通过游标cursor查询SQL语句将结果存储在Excel文件中,其中Excel的生成使用xlwt实现的。
作者:Mr' fan
时间:2018年3月
'''
import pymysql
import xlwt
import datetime
#def func():
#连接mysql数据库。
conn = pymysql.connect(host='127.0.0.1', port=6606, user='root', passwd='PxxxxxSH', db='nc', charset='utf8')
#使用cursor()方法获取操作游标。
cursor = conn.cursor()
#effect_row = cursor.execute("select a.username,count(if(b.ntype='18060',true,null)),count(if(b.ntype='1001',true,null)) from nctermnetlog_if_201803 a,ncsnettype b where a.nettype=b.ntype and stime>unix_timestamp('2018-03-18 09:00:00') group by a.username")
#使用execute方法执行SQL语句,并将统计结果存储在effect_row变量中。
effect_row = cursor.execute("select a.username,a.mac,count(if(b.ntype='18060',true,null)),count(if(b.ntype='1001',true,null)),count(if(b.ntype='18079',true,null)),count(if(b.ntype='18080',true,null)),count(if(b.ntype='7633',true,null)),count(if(b.ntype='21368',true,null)),count(if(b.ntype='21400',true,null)),count(if(b.ntype='23581',true,null)),count(if(b.ntype='21416',true,null)) from nctermnetlog_if_201803 a,ncsnettype b where a.nettype=b.ntype and stime>unix_timestamp('2018-03-21 00:00:00') and stime<unix_timestamp('2018-03-22 00:00:00') group by a.username")
print effect_row  #打印总行数
#获取所有的记录结果
row_3 = cursor.fetchall()
#print row_3  #打印统计结果
#获取上述SQL语句中的检索条件名称(将要成为Excel第一行的表头)。
fields = cursor.description
#将字段写入到EXCEL新表的第一行 。
workbook = xlwt.Workbook(encoding='utf-8')
#创建Excel中的一个sheet,并命名且为可重写状态。
sheet = workbook.add_sheet('result_count',cell_overwrite_ok=True)
#构造一个列表VnameList,用于将上述表头重命名,一定要一一对应。
VnameList = [u"用户名","MAC",u"微信ID","QQ",u"新浪微博",u"腾讯微博",u"腾讯视频",u"京东商城",u"淘宝",u"今日头条",u"美团"]
#将上述list中的虚拟身份依次填入Excel中去。
for field in range(0,len(VnameList)):
#sheet.write(0,field,fields[field][0])
sheet.write(0,field,VnameList[field].encode("utf-8"))

#根据横纵坐标依次录入查询到的信息值。
row = 1
col = 0
for row in range(1,len(row_3)+1):
for col in range(0,len(fields)):
sheet.write(row,col,u'%s'%row_3[row-1][col])
#格式化时间输出,用于给Excel起名时使用。
sheet_time = datetime.datetime.now()
book_mark = sheet_time.strftime('%Y%m%d')
#将Excel文件保存下来
workbook.save('./Count_result%s.xls'%book_mark.encode("utf-8"))
#workbook.save(r'./Count_result.xls'.encode("utf-8"))
#依次做提交和关闭操作。
conn.commit()
cursor.close()
conn.close()

#if __name__=="__main__":
#  func()

原文地址:https://www.cnblogs.com/ddpeng/p/8645424.html