python-excel模块

 1 import pymysql,xlwt
 2 def export_excel(table_name):
 3     host, user, passwd, db = '118.24.3.40', 'jxz', '123456', 'jxz'
 4     coon = pymysql.connect(user=user,host=host,port=3306,passwd=passwd,db=db,charset='utf8' )
 5     cur = coon.cursor()
 6     sql = 'select * from %s;'%table_name
 7     cur.execute(sql)  # 执行sql
 8     fileds = [filed[0] for filed in cur.description]#所有字段
 9     all_data = cur.fetchall()
10     book = xlwt.Workbook()
11     sheet = book.add_sheet('sheet1')
12     # col = 0
13     # for filed in fileds:#写表头
14     #     sheet.write(0,col,filed)
15     #     col+=1
16     for col,filed in enumerate(fileds):#写表头
17         sheet.write(0,col,filed)
18     row = 1#控制行数
19     for data in all_data:#行数
20         for col, filed in enumerate(data):#列数
21             sheet.write(row, col, filed)
22         row+=1#每次写完一行,行数加1
23     book.save('%s.xls'%table_name)
24 export_excel('app_student')

猜你喜欢

转载自www.cnblogs.com/ymany/p/9026656.html