Python small exercise _ database table data export to excel

Requirement: As long as a table name is passed in, all data can be imported, and the field name is the header of excel

1. To dynamically obtain the target field cur.descrption can obtain the fields of the table

fileds = [filed[0] for filed in cur.description]

The following figure can get the table structure and take out the header

2. Get data select * from %s;%table_name

3. Export to excel

 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 inenumerate(fileds):    #Write the header, 
20          sheet.write(0,col,filed) #These    two lines of code are equivalent to the above four lines of code 
21  
22      # print(all_data) 
23      row = 1    #The first line 
24      for data in all_data: #Line   25 for col ,filed in enumerate(data):    #Control column 26 sheet.write ( row 
            ,col,filed)
 27          row+=1 #Each time a line is written, add one to the number of lines 28 29      book. save( ' %s.xls ' %         
 
 
table_name)
30 
31 export_excel('app_student')

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325794011&siteId=291194637