#-*- coding:utf-8 -*-
from xlwt import *
importxlrdimportpymysql
#建立mysql连接
conn= pymysql.connect(host='127.0.0.1',user='root', passwd='1234', db='test', charset='utf8')
cur=conn.cursor()defSQL(cur,sql):
cur.execute(sql);return(cur);
#执行sql语句
a=SQL(cur, r"select * from test;")
#打开一个execle文档
w= Workbook(encoding='utf-8')
ws= w.add_sheet(u"xls")
i=1f= ['id', '名字']
#通过循环,将列明插入进去。
g=0for x inf:
fnt=Font()
style=XFStyle()
style.font=fnt
ws.write(0, g, x)
ws.row(i).set_style(style)
g= g + 1
try:
#遍历sql语句查询到的内容for b ina:
fnt=Font()
style=XFStyle()
style.font=fntfor f inrange(0,len(b)):
ws.write(i, f,'%s' %b[f])
ws.row(i).set_style(style)
i= i + 1
ifb:
w.save(u"测试.xls")exceptException as e:print(e)
cur.close()
conn.close()