# -*- 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()