使用python腳本從數據庫導出數據到excel


python從數據庫導出數據到excel

最近需要從數據庫里導出一些數據到excel,剛開始我是使用下面的命令

select * from xxx where xxx into outfile 'xxx.xls'

結果報錯

ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

除了這個錯誤,可能還會報access deny的錯誤,關於access deny的錯誤,有一篇博客講的很詳細:https://daizj.iteye.com/blog/2174972

請教同事后發現他們都是用腳本來導出數據,這樣安全又方便,於是自己也整了一個,記錄一下


1)安裝easy_install

由於公司使用的是老舊的python2,所以還是使用easy)install來安裝包,如果沒有安裝easy_install,需要安裝easy_install

yum install python-setuptools

2)安裝pymysql和xlwt

使用easy_install安裝pymysql和xlwt

easy_install pymysql
easy_install xlwt

使用pip也可以安裝

pip install pymysql
pip isntall xlwt

使用pip安裝如果報錯

Fatal error in launcher: Unable to create process using '"C:\Python27\python.exe" "C:\Python27\Scripts\pip.exe" install pymysql'


可以將在前面加上python2 -m (啟動python環境)
python2 -m pip install pymysql

3)編寫腳本

# --*-- coding:utf8 --*--
import pymysql, xlwt


def export_excel(table_name):
    # 連接數據庫,查詢數據
    host, user, passwd, db='127.0.0.1','root','123','xxx'
    conn = pymysql.connect(user=user,host=host,port=3306,passwd=passwd,db=db,charset='utf8')
    cur = conn.cursor()
    sql = 'select * from %s' % table_name
    cur.execute(sql)  # 返回受影響的行數
    
    fields = [field[0] for field in cur.description]  # 獲取所有字段名
    all_data = cur.fetchall()  # 所有數據
    
    # 寫入excel
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    
    for col,field in enumerate(fields):
        sheet.write(0,col,field)
    
    row = 1
    for data in all_data:
        for col,field in enumerate(data):
            sheet.write(row,col,field)
        row += 1
    book.save("%s.xls" % table_name)
    

if __name__ == '__main__':
    export_excel('app1_book')

4)啟動腳本導出數據

python2 export.py


免責聲明!

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



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