一次Python操作数据库和写入excel的过程

 

  需求:传入一个表名后,将表中所有数据写入excel中。

  使用了pymysql,xlwt,需要自行安装。

import pymysql,xlwt
def sql_into_excel(table_name):
        db_info = {'user': 'xxx', 'password': '123456','host': '8.8.8.8', 'db': 'asd', 'port': 3306, 'charset': 'utf8','autocommit': True}
        conn = pymysql.connect(**db_info)  # 建立连接
        cur = conn.cursor(pymysql.cursors.DictCursor) #获取表头的游标

        sql = 'select * from %s' %(table_name) #如果参数在实际查询中需要用‘’,在SQL中写法:'%s'
        cur.execute(sql)
        all = cur.fetchall()

        cur.close()
        conn.close()

        key = []
        for i in all[0]:
                key.append(i)

        book = xlwt.Workbook()
        sheet = book.add_sheet('sheet1')

        for j in range(len(key)):
                sheet.write(0,j,key[j])
                for x in range(len(all)):
                        a = key[j]
                        sheet.write(x+1,j,all[x][a])

        book.save('test.xls')

sql_into_excel('table_name')

 

posted @ 2019-11-01 11:40  会武术的跳跳虎  阅读(419)  评论(0编辑  收藏  举报