一個簡單的使用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: jiajunp@163.com @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')