python读取数据库表数据并写入excel
一个简单的使用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数据库中表数据
sql = ‘select * from %s;‘ %table_name #需要写入excel表数据 #读取数据 cur.execute(sql) #读取数据 fileds = [filed[0] for filed in cur.description] #读取表结构定义 all_date = cur.fetchall() #所有数据 for result in all_date: print(result)
3、数据写入excel
book = xlwt.Workbook() #创建一个book sheet = book.add_sheet(‘result‘) #创建一个sheet表 for col,filed in enumerate(fileds): sheet.write(0,col,filed) #将表字段描述写入excel第一行 #从第一行开始写 row = 1 for data in all_date: for col,filed in enumerate(data): sheet.write(row,col,filed)#将数据写入excel单元格中 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: @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‘)
相关推荐
diyanpython 2020-11-05
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20