匯出mysql資料,利用pandas產生excel文檔,並發送郵件

來源:互聯網
上載者:User

標籤:python   pandas   

首先得安裝各種庫。。。。


諸如mysql,pandas,numpy之類的了

我使用的pandas版本為pandas (0.16.2)

其中openpyxls版本為openpyxl (1.8.6)


    其實到處mysql查詢結果匯出當然可以使用諸如sqllog,Navicat之類的用戶端直接匯出,簡單快捷,下面的代碼只是在需要定時並且以某種格式定期發送sql查詢結果的環境下才存在的。

    註:再者pandas當然還可以結合matplotlib產生漂亮的餅狀圖或者柱狀圖,只不過筆者暫時沒有這個需求,所以沒有寫產生圖片的部分


放代碼:

#!/usr/bin/env python# -*- coding: utf-8 -*-import pandasimport pandas as pdimport MySQLdbimport MySQLdb.cursorsimport osimport datetimefrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport smtplib#返回SQL結果的函數def retsql(sql):    db_user = MySQLdb.connect(‘IP‘,‘使用者名稱‘,‘密碼‘,‘j資料庫名(可以不指定)‘,cursorclass=MySQLdb.cursors.DictCursor(設定返回結果以字典的格式))    cursor = db_user.cursor()    cursor.execute("SET NAMES utf8;"(設定字元集為utf-8,不然在返回的結果中會顯示亂碼,即使資料庫的編碼設定就是utf-8))     cursor.execute(sql)    ret = cursor.fetchall()    db_user.close()    return ret#產生xls檔案的函數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#發送郵件的函數##傳入主題,顯示名,目標郵箱,附件名def sendm(sub,cttstr,to_list,file):    msg = MIMEMultipart()    att = MIMEText(open(file,‘rb‘).read(),"base64","utf-8")    att["Content-Type"] = "application/octet-stream"    att["Content-Disposition"] = ‘attachment; filename="sql查詢結果.xlsx"‘    msg[‘from‘] = ‘寄件者地址‘    msg[‘subject‘] = sub    ctt = MIMEText(cttstr,‘plain‘,‘utf-8‘)    msg.attach(att)    msg.attach(ctt)    try:        server = smtplib.SMTP()        #server.set_debuglevel(1)  ###如果問題可開啟此選項以便調試        server.connect("mail.example.com",‘25‘)        server.starttls()   ###如果開啟了ssl或者tls加密,開啟加密        server.login("可用信箱使用者名","密碼")        server.sendmail(msg[‘from‘],to_list,msg.as_string())        server.quit()        print ‘ok!!!‘    except Exception,e:        print str(e)###想要查詢的sql語句sql="""sql語句"""#內送郵件的使用者列表to_list = [‘[email protected]‘, ‘[email protected]‘]#執行sql並將結果傳遞給retret = retsql(sql)#將結果檔案路徑結果傳給retfileretfile = retxls(ret,"1")#發送郵件#發送sql語句內容sendm(sub1,sub1,to_list,retfile1)

    雖然上述代碼還有很大的改動空間,但是能用並且已經用了,又不是很重要的部分,就不繼續改進了。

本文出自 “又耳的筆記本” 部落格,請務必保留此出處http://youerning.blog.51cto.com/10513771/1708941

匯出mysql資料,利用pandas產生excel文檔,並發送郵件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.