需求:只要傳入一個表名,就能把全部的數據導入出來,字段名是excel的表頭mysql
1.要動態獲取到標的字段 cur.descrption能獲取到表的字段sql
fileds = [filed[0] for filed in cur.description]app
下圖能夠獲取表結構,並取出表頭fetch
2.獲取數據 select * from %s;%table_namespa
3.導出到excelexcel
1 import pymysql,xlwt 2 def export_excel(table_name): 3 coon =pymysql.connect( 4 user='xxx',passwd='123456',host='xxx.xxx.xxx.xxx',port=3306, 5 db='xxx',charset='utf8' 6 ) 7 cur = coon.cursor() 8 sql = 'select * from %s;'%table_name 9 cur.execute(sql) #執行sql 10 fileds = [filed[0] for filed in cur.description] #全部的字段 11 all_data = cur.fetchall() 12 13 book = xlwt.Workbook() 14 sheet = book.add_sheet('sheet1') 15 # col = 0 16 # for filed in fileds: 17 # sheet.write(0,col,filed) 18 # col+=1 19 for col,filed in enumerate(fileds): #寫表頭的, 20 sheet.write(0,col,filed) #這兩行代碼等同於上面四行代碼 21 22 # print(all_data) 23 row = 1 #第一行 24 for data in all_data: #行 25 for col,filed in enumerate(data): #控制列 26 sheet.write(row,col,filed) 27 row+=1 #每次寫完一行,行數加一 28 29 book.save('%s.xls'%table_name) 30 31 export_excel('app_student')