將資料庫資料入excel中併發送郵件
阿新 • • 發佈:2018-11-07
我們有個政府專案,程式碼和資料庫都在政府那邊,我就開了一個後門,每天定時將資料庫資料發到我們這邊來,然後定時把這個檔案再刪除掉,在中秋這一天專案經理給我打電話問我說資料庫資料的情況,並且讓我們這邊一個開發人員幫忙統計增量是多少,我就萌生了一個想發,過節都不讓人過好,還想著公司的事情,於是自己就打算寫一個功能,將資料統計出來,然後呼叫郵件伺服器傳送給專案經理
我是運維出身,python都是自學的,好多東西寫的不是很規範,但是功能已經實現了,指令碼內容如下:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import pymysql,time
import xlwt
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.header import Header
src="/home/email/data"
class writeExcel(object):
'''將資料庫資料寫入到excel中'''
def __init__(self):
self.workbook = xlwt.Workbook()
def writefile(self,data,field): #data為查查詢結果,field為工作簿名
sheet = self.workbook.add_sheet(field, cell_overwrite_ok=True)
for field in range(0, len(fields)):
sheet.write(0, field, fields[field][0])
# 獲取並寫入資料段資訊
row = 1
col = 0
for row in range(1, len(data) + 1):
for col in range(0, len(fields)):
sheet.write(row, col, u'%s' % data[row - 1][col])
def savaDate(self):
self.workbook.save(r'%s/%s.xlsx' %(src,time.strftime('%Y%m%d')))
def email(email_list,content,subject="企業資料%s" %time.strftime('%Y%m%d')):
'''郵件伺服器'''
msg = MIMEMultipart() #建立一個帶有附件的例項
msg['From'] = formataddr(["冠通新創", ' [email protected]']) #發件人顯示的名稱和地址
msg['Subject'] = Header(subject, 'utf-8')
msg.attach(MIMEText(content,'plain','utf-8')) #傳送主體
# 構造附件
att1 = MIMEText(open('%s/%s.xlsx' % (src,time.strftime('%Y%m%d')), 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="%s.xlsx"' %time.strftime('%Y%m%d')
msg.attach(att1)
#SMTP服務區
server = smtplib.SMTP("smtp.qiye.163.com",25) #網易雲的smtp伺服器
server.login(' [email protected]','1234567890') #登陸網易雲的企業郵箱和密碼
server.sendmail('[email protected]',email_list,msg.as_string())
server.quit()
#資料庫連線資訊
PY_MYSQL_CONN_DICT = {
"host": '127.0.0.1',
"port": 3306,
"user": 'root',
"passwd": '1234567890',
"db": 'food-user',
"charset": 'utf8'
}
conn = pymysql.connect(**PY_MYSQL_CONN_DICT) #連線資料庫
cursor = conn.cursor() #建立遊標
sqlOne="""
select DISTINCT a.companyname,c.username from `food-user`.companyinfo a
INNER JOIN `product-company`.supplier b on a.id = b.company_id
INNER JOIN `food-user`.`food_user` c on a.id = c.company_id
where a.id not in (select companyid from `food-user`.testCompanyId)
ORDER BY c.username asc
"""
sqlTwo="""
select DISTINCT a.companyname,c.username from `food-user`.companyinfo a
INNER JOIN `currency-company`.supplier b on a.id=b.company_id
INNER JOIN `food-user`.`food_user` c on a.id = c.company_id
where a.id not in (select companyid from `food-user`.testCompanyId)
ORDER BY c.username asc;
"""
sqlThree="""
select DISTINCT a.companyname,c.username from `food-user`.companyinfo a
INNER JOIN `restaurant_company`.supplier b on a.id=b.companyid
INNER JOIN `food-user`.`food_user` c on a.id = c.company_id
where a.id not in (select companyid from `food-user`.testCompanyId)
ORDER BY c.username asc;
"""
cursor.execute(sqlOne)
results = cursor.fetchall()
cursor.execute(sqlTwo)
results2=cursor.fetchall()
cursor.execute(sqlThree)
results3=cursor.fetchall()
# 獲取MYSQL裡面的資料欄位名稱
fields = cursor.description
#將資料寫入到excel中
obj = writeExcel()
obj.writefile(results,'product')
obj.writefile(results2,'currency')
obj.writefile(results3,'restaurant')
obj.savaDate()
conn.commit()
cursor.close()
conn.close()
#傳送郵件
email([' [email protected]'],'企業資料%s' %time.strftime('%Y%m%d'))