python实现查询的数据写入到excel

#coding=utf-8
import sys
import xlwt
import pymysql as MySQLdb #这里是python3 如果你是python2.x的话,import MySQLdb
import datetime


host = '192.168.10.109'
user = 'root'
pwd = ''
port = 3306
db = 'com66nao_mi'
sheet_name = 'report'
out_path = r'D:\SQL\aaa'+'.xls'
print(out_path)
sql = '''select * from mi_orgs;'''

def export():
conn = MySQLdb.connect(host,user,pwd,db,charset='utf8') 
cursor = conn.cursor() 
count = cursor.execute(sql) 
print("查询出" + str(count) + "条记录")

#来重置游标的位置 
cursor.scroll(0,mode='absolute')
#搜取所有结果 
results = cursor.fetchall()

# 获取MYSQL里面的数据字段名称
fields = cursor.description
workbook = xlwt.Workbook() # workbook是sheet赖以生存的载体。 
sheet = workbook.add_sheet(sheet_name,cell_overwrite_ok=True)

# 写上字段信息 
for field in range(0,len(fields)): 
sheet.write(0,field,fields[field][0])

# 获取并写入数据段信息 
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]) 

workbook.save(out_path)

#结果测试
if __name__=="__main__":
export()

posted @ 2018-12-03 19:42  陈晓猛  阅读(2108)  评论(0编辑  收藏  举报