一个简单的使用python读取mysql数据并写入excel中实例
1、python连接mysql数据库
conn = pymysql.connect(user=‘root‘,host=‘127.0.0.1‘,port=3306,passwd=‘root‘,db=‘python‘,charset=‘utf8‘) #连接数据库 cur = conn.cursor()
2、读取mysql数据库中表数据
1 sql = ‘select * from %s;‘ %table_name #需要写入excel表数据 2 #读取数据 3 cur.execute(sql) #读取数据 4 fileds = [filed[0] for filed in cur.description] #读取表结构定义 5 all_date = cur.fetchall() #所有数据 6 for result in all_date: 7 print(result) 8
3、数据写入excel
1 book = xlwt.Workbook() #创建一个book 2 3 sheet = book.add_sheet(‘result‘) #创建一个sheet表 4 5 for col,filed in enumerate(fileds): 6 sheet.write(0,col,filed) #将表字段描述写入excel第一行 7 8 #从第一行开始写 9 10 row = 1 11 for data in all_date: 12 for col,filed in enumerate(data): 13 sheet.write(row,col,filed)#将数据写入excel单元格中 14 row = 1
4、保存excel
book.save(‘%s.xls‘ %table_name)
5、完整代码
#!/usr/bin/env python # -*- coding: utf-8 -*- ‘‘‘ @Time : 2020/1/1 18:08 @Author : Jason.Jia @contact: [email protected] @Version : 1.0 @file :mysql_write_excel.py @desc : 从mysql读取数据,写入excel中 ‘‘‘ import pymysql,xlwt def export_excel(table_name): conn = pymysql.connect(user=‘root‘,host=‘127.0.0.1‘,port=3306,passwd=‘root‘,db=‘python‘,charset=‘utf8‘) cur = conn.cursor() sql = ‘select * from %s;‘ %table_name #读取数据 cur.execute(sql) fileds = [filed[0] for filed in cur.description] all_date = cur.fetchall() #所有数据 for result in all_date: print(result) #写excel book = xlwt.Workbook() #创建一个book sheet = book.add_sheet(‘result‘) #创建一个sheet表 for col,filed in enumerate(fileds): sheet.write(0,col,filed) #从第一行开始写 row = 1 for data in all_date: for col,filed in enumerate(data): sheet.write(row,col,filed) row = 1 book.save(‘%s.xls‘ %table_name) if __name__ == ‘__main__‘: export_excel(‘stocks‘)