# 需求:只要你传入一个表名,就能把所有的数据导入出来,字段名是excel的表头
# 1、要动态获取到表的字段
# cur.description能获取到表的字段
# fileds = [filed[0] for filed in cur.description]
# 2、获取数据了
# select * from "%s" % table_name
# 3、循环写入excel
# for i in range(5):
# for j in range(3):
# print(j)
import pymysql,xlwt
def export_exel(tale_name):
import pymysql
host, user, passwd, db = '118.xx.xx.xx', 'xx', '123456', 'xxx'
coon = pymysql.connect(
host=host,user=user,passwd=passwd,db=db,port=3306,charset='utf8'
)
cur = coon.cursor()# 建立游标
sql = 'select * from %s;'%tale_name
cur.execute(sql) # 执行sql
# cur.description所有的字段(('id', 3, None, 11, 11, 0, False),()……)
fileds=[filed[0] for filed in cur.description]
# print(fileds) #['id', 'name', 'sex', 'age', 'addr', 'grade', 'phone', 'gold']
all_data=cur.fetchall()#获取到SQL执行的全部结果,它把数据库表里面的每一行数据放到一个LIST里面
book = xlwt.Workbook() # 新建一个excel
sheet = book.add_sheet('sheet1') # 加sheet页
# col=0 #列
for col,filed in enumerate (fileds):#写表头的,col接收的下标,filed接收的是内容
sheet.write(0,col,filed)
# col+=1
print(all_data)
row=1 #行数
for data in all_data:#行 all_data((1, '小黑马', '男', 28, '河南省济源市北海大道32号'),……)
for col, filed in enumerate(data):#控制列
sheet.write(row, col, filed)
row+=1 #每次写完一行,行就加1
book.save('%s.xls'%tale_name)
export_exel('app_student')
#
# # enumerate()#循环的时候,直接获取到下标和值
# fileds = ['id','name','sex','addr','gold','score']
# for index,filed in enumerate(fileds):
# print(index,filed)