需求:

只要传入一个表名,就能把所有数据导入出来,字段名是excel的表头

1、要动态获取到表的字段cur.description能获取到表的字段

   fileds = [filed[0] for filed in cur.description] 列表生成式获取表头

2、获取数据 select * from "%s" %table_name

3、循环写入excel

   enumerate打印列表下标及元素,循环列表,下标自增实现列自增

实现:

def export_excel(table_name):
    import pymysql,xlwt
    host, usser, passwd, db = '127.0.01','root','123456','data'#定义多个变量
    conn = pymysql.connect(host = host,user = usser, passwd = passwd,port = 3306,db=db,charset = 'utf8')
    cur = conn.cursor()#建立游标,指定游标类型返回不要是字典
    sql = 'select * from %s;'%table_name
    cur.execute(sql) # 执行sql
    all_data = cur.fetchall()
    fileds = [filed[0] for filed in cur.description]#所有的字段名,获取表头
    cur.close()
    conn.close()
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    for col,filed in enumerate(fileds):#写表头
        sheet.write(0,col,filed)
    row = 1#控制行数
    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('stu_info')

 

posted on 2018-05-07 19:13  忻冉然  阅读(229)  评论(0编辑  收藏  举报