使用pandas從mysql讀取并寫入到excel文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas
import pandas as pd
import MySQLdb
import MySQLdb.cursors
import os
import datetime


#返回SQL結(jié)果的函數(shù)
def retsql(sql):
    db_user = MySQLdb.connect(‘IP‘,‘用戶名‘,‘密碼‘,‘j數(shù)據(jù)庫名(可以不指定)‘,cursorclass=MySQLdb.cursors.DictCursor(設(shè)置返回結(jié)果以字典的格式))
    cursor = db_user.cursor()
    cursor.execute("SET NAMES utf8;"(設(shè)置字符集為utf-8,不然在返回的結(jié)果中會顯示亂碼,即使數(shù)據(jù)庫的編碼設(shè)置就是utf-8)) 
    cursor.execute(sql)
    ret = cursor.fetchall()
    db_user.close()

    return ret

#生成xls文件的函數(shù)
def retxls(ret,dt):
    file_name = datetime.datetime.now().strftime("/path/to/store/%Y-%m-%d-%H:%M") + dt + ".sql.xlsx"
    dret = pd.DataFrame.from_records(ret)
    dret.to_excel(filename,"Sheet1",engine="openpyxl")###z注意openpyxl這個庫可能在生成xls的時候出錯,pip install openpyxls==1.8.6,其他版本似乎與pandas有點沖突,安裝1.8.6的即可

    print "Ok!!! the file in",file_name
    return filename
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容