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數據庫中表數據 

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')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM