python mysql到处excel

#coding:utf8
'''
mysql到处数据到excel脚本

'''
import xlwt
import MySQLdb
import datetime

conn = MySQLdb.connect(host = '192.168.96.150',port = 3306,user = 'root',passwd = 'mysql',db = 'taoyuan')
cur = conn.cursor()
count = cur.execute('select * from yhb')#记录条数
print count
print 'has %s record' %count

#重置游标位置
cur.scroll(0,mode='absolute')
results = cur.fetchall()#获取所有结果

fields = cur.description
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('test',cell_overwrite_ok=True)#将表加入到记录簿里面

for field in range(0,len(fields)):
sheet.write(0,field,fields[field][0])#将表字段写入excel中

row = 1#从第二行开始,第一行为表头
col = 0

for row in range(1,len(results)+1):
for col in range(0,len(fields)):
sheet.write(row,col,u'%s'%results[row-1][col])
#到处路径
out_path = 'D:/xls/'+ datetime.datetime.now().strftime('%Y%m%d') + '.xls'
wbk.save(out_path)


posted @ 2017-11-30 19:36  jack-toy  阅读(151)  评论(0编辑  收藏  举报