import xlwt
# 引入pymysql包
import pymysql
# 连接数据库并打开library数据库
sql="SELECT * FROM\
user1;"
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='test')
# 获取游标对象
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 执行SQL语句
cur.execute(sql)
fields = [field[0] for field in cur.description] # 获取所有字段名
all_data = cur.fetchall() # 所有数据
print(fields)
print(all_data)
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
'''
for col,field in enumerate(fields):
sheet.write(0,col,field)
'''
for i in range(0, len(fields)):
sheet.write(0,i,fields[i])
row = 1
for data in all_data:
for col,field in enumerate(data):
sheet.write(row,col,data[field])
print(data[field])
row += 1
book.save("这是你想要的数据.xls")
# 关闭游标
cur.close()
# 关闭数据库连接
conn.close()