import pymysql,xlwt
def con_mysql(sql):
conn = pymysql.connect(host='211.149.218.16', user='jxz', password='123456', db='jxz', charset='utf8')
cur = conn.cursor()
cur.execute(sql)
res = cur.fetchall()
cur.close()
conn.close()
return res
def write_excel(filename, content):
book = xlwt.Workbook() # 创建一个excel
sheet = book.add_sheet('学生信息') # 添加一个sheet页,sheet可以改成别的名字
title = ['id', 'name']
i = 0
for t in title:
sheet.write(0, i, t)
i = i + 1
line_no = 1
for line in content:
row = 0
for j in line:
sheet.write(line_no, row, j)
row = row + 1
line_no = line_no + 1
book.save(filename)
res = con_mysql('select * from stu;') # 查询结果返回到res里
write_excel('haha.xls', res) # 把内容写到文件里