操作excel--day7

需求:只要你传入一个表名,就能把所有的数据导入出来写入excel,字段名是excel的表头
分析:
  1、要动态获取到表的字段 cur.description能获取到表的字段
  fileds = [ filed[0] for filed in cur.description ] #列表生成式写法(其他章节有专门介绍)
  2、获取数据 select * from "%s" % table_name
  3、循环写入excel
代码及解析如下:
import pymysql,xlwt
def export_excel(table_name):
host, user, passwd, db = '118.24.3.xx', 'jxzx', '123456', 'jxzx'
coon = pymysql.connect(user=user, host=host, port=3306, passwd=passwd, db=db, charset='utf8')
cur = coon.cursor()
sql = 'select * from %s;'%table_name
cur.execute(sql) # 执行sql
fileds = [filed[0] for filed in cur.description] #所有的字段(表头)
all_data = cur.fetchall()
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
# col = 0
# for filed in fileds: #循环写表头
# sheet.write(0,col,filed)
# col+=1
for col,filed in enumerate(fileds): #循环写表头,其中enumerate方法可以自动使col自动+1循环写,等同于上面注释掉的四行内容写法
sheet.write(0,col,filed)
row = 1 #行数,从第一行开始,第0行已经被表头写入
# print(all_data) #查看所有的数据及格式,是二维数组
# ((1, '小黑马', '男', 28, '河南省济源市北海大道32号', '天蝎座', '18002531114', 617741546),
# (1, '小黑马', '男', 28, '河南省济源市北海大道32号', '天蝎座', '18002531114', 617741546),
for data in all_data: #二维数组,控制行
for col,filed in enumerate(data): #控制列
sheet.write(row,col,filed)
row+=1 #每次写完一行,行就加1
book.save('%s.xls'%table_name)
export_excel('app_student')

部分结果如下图:



猜你喜欢

转载自www.cnblogs.com/fancyl/p/9008087.html
今日推荐