# -*- coding:utf-8 -*-
from xlwt import *
import xlrd
import pymysql
#创建mysql链接
conn = pymysql.connect(host='127.0.0.1',user='root', passwd='1234', db='test', charset='utf8')
cur = conn.cursor()
def SQL(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=1
f = ['id', '名字']
#经过循环,将列明插入进去。
g = 0
for x in f:
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 in a:
fnt = Font()
style = XFStyle()
style.font = fnt
for f in range(0,len(b)):
ws.write(i, f, '%s' %b[f])
ws.row(i).set_style(style)
i = i + 1
if b:
w.save(u"测试.xls")
except Exception as e:
print(e)
cur.close()
conn.close()