【python】自動(dòng)生成excel并發(fā)送可視化郵件

從數(shù)倉(cāng)取數(shù)加工處理后放在excel,進(jìn)一步處理后分析數(shù)據(jù),生成可視化圖片,形成報(bào)告發(fā)送郵件等內(nèi)容,以下的python腳本,自動(dòng)化處理上面的整個(gè)流程。

PART 1 數(shù)倉(cāng)取數(shù)到EXCEL

###############################################################################
## ********************************   生成excel    **************************##
###############################################################################
import pandas as pd
from sqlalchemy.engine import create_engine
import xlsxwriter
import time

## ***************************    向excel添加數(shù)據(jù)表1     *******************##
# 準(zhǔn)備語(yǔ)句(不能帶分號(hào))
sql_1 = """
            select 
                *
            from  t
            order by data_date asc
        """
        
presto_engine = create_engine('jdbc://110.120.119.115:8866/hive') 

# 從數(shù)據(jù)庫(kù)獲取數(shù)據(jù)
df_1 = pd.read_sql(sql_1, presto_engine)
headline_1 = df_1.columns.values.tolist()         #tb1獲取列名

## 生成excel文件
# 需要修改(導(dǎo)出的文件路徑)
out_path = r'C:\Users\Dell\Desktop\Day_Report'+  '(' + time.strftime("%Y-%m-%d") +')' + '.xlsx'  
workbook = xlsxwriter.Workbook(out_path , {'strings_to_numbers': True})       # workbook是sheet賴以生存的載體。

# 定義sheet的名字
sheet1 = workbook.add_worksheet('01sheet')

# 定義表格樣式
format1 = workbook.add_format({'align': 'center', 'bg_color': '#83ABED', 'bold': 'true', 'border': 1})
format2 = workbook.add_format({'border': 1}) 
format3 = workbook.add_format({ 'border': 1 , 'num_format': '##.##%'})

#在excel文件中寫(xiě)入表格數(shù)據(jù)
def report1():
    sheet1.set_column(0, df_1.shape[1], 12)                    # 設(shè)置表頭列寬為12

    #寫(xiě)入數(shù)據(jù)表格表頭
    #sheet1.merge_range('A1:D1','信息',format1)      # 合并單元格寫(xiě)入表頭
    sheet1.write_row('A1',headline_1,format1)           # 寫(xiě)入字段列名

    #寫(xiě)入表格數(shù)據(jù)
    for rows in range(1,len(df_1)+1):
        for cols in range(0,df_1.shape[1]):
            if cols in range(0,4) :
                sheet1.write(rows, cols, df_1.iloc[rows-1,cols],format2)          
            else:
                sheet1.write(rows, cols, df_1.iloc[rows-1,cols],format3)  # 百分比形式顯示

####################   加入圖形1   ######################
# 圖表類型 柱形圖
chart1 = workbook.add_chart({'type': 'column'})
# 圖形大小
chart1.height = 500
chart1.width  = 900
# 橫軸種類和數(shù)值
chart1.add_series({'name':        'APPLY人數(shù)', 
                   'categories': ['01sheet',1,0,7,0], 
                   'values':     '=01sheet!$B$2:$B$8',
                   'data_labels': {'value': True}
                   })
chart1.add_series({'name':        'CROSS人數(shù)',
                   'categories': ['01sheet',1,0,7,0], 
                   'values':     '=01sheet!$C$2:$C$8',
                   'data_labels': {'value': True}
                   })
chart1.add_series({'name':        'SUCC人數(shù)',
                   'categories': ['01sheet',1,0,7,0], 
                   'values':     '=01sheet!$D$2:$D$8',
                   'data_labels': {'value': True}
                   })
# 圖形名稱
chart1.set_title({'name': 'APPLY-CROSS人數(shù)'})
# 類別所在位置
chart1.set_legend({'position': 'bottom'})
# 圖形插入位置
sheet1.insert_chart('G1', chart1)

if __name__=="__main__":
    report1()  
    workbook.close()

print('-----------------success!------------------')

PART 2 從EXCEL截圖并保存在本地

###############################################################################
## ********************************   excel截圖     *************************##
###############################################################################
import win32com.client as win32   # 打開(kāi)excel文件
from PIL import ImageGrab         #用于獲取復(fù)制的圖片
import pythoncom
import time

pythoncom.CoInitialize()        # excel多線程相關(guān)
root_path = "C:\\Users\\Dell\\Desktop\\"

#獲取Excel
excel = win32.Dispatch('Excel.Application')
excel.Visible = True
#excel.DisplayAlerts = False
# 打開(kāi)excel文件
wb = excel.Workbooks.Open(r'C:\Users\Dell\Desktop\Day_Report'+'('+time.strftime("%Y-%m-%d") +')'+ '.xlsx') 

################ 制作圖1 ################
ws_1 = wb.Worksheets('01sheet')        # 獲取Sheet
# 復(fù)制圖片區(qū)域
ws_1.Range('G1:T25').CopyPicture()
ws_1.Paste(ws_1.Range('V1'))            # 將圖片移動(dòng)到
# 定義圖片名稱
#excel.Selection.ShapeRange.Name = 'pic_1'     # 選擇區(qū)域重命名
ws_1.Shapes('Picture 1').Copy()
img_1 = ImageGrab.grabclipboard()
# 圖片另存為本地
img_1.save(root_path + 'regist-cross' +'.jpg')

wb.Close(SaveChanges=0)       #關(guān)閉sheet,不保存
excel.Quit()                  #關(guān)閉excel
pythoncom.CoUninitialize()    #關(guān)閉多線程

print('--------------------success----------------------')

PART 3 發(fā)送郵件

###############################################################################
## *******************************   發(fā)送郵件     ****************************##
###############################################################################

from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
import smtplib
import time

def send_mail():
    email_host = 'smtp.exmail.qq.com'      # 服務(wù)器地址   qq郵箱"smtp.qq.com"都需要開(kāi)通smtp權(quán)限
    sender     = ''      # 發(fā)件人(自己的郵箱)
    password   = ''      # 密碼(自己郵箱的登錄密碼)
    receiver   = ''      # 收件人   

    msg = MIMEMultipart()
    msg['Subject'] = ''      # 標(biāo)題
    msg['From'] = ''         # 郵件中顯示的發(fā)件人別稱
    msg['To'] = ''           # 收件人別稱

    # 郵件正文內(nèi)容,可以插入圖片
    mail_msg = '''
            <p> Dear all: </p>
            <p> &emsp;&emsp; 以下是******報(bào)表,請(qǐng)查收。</p>
            <p>1.*********** :</p>
            <p><img src="cid:image1"></p>
            <p>2.*********** :</p>
            <p><img src="cid:image2"></p>
            '''

    msg.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    # 指定圖片為當(dāng)前目錄
    fp_1 = open(r'C:\Users\Dell\Desktop\regist-cross.jpg', 'rb')
    msgImage_1 = MIMEImage(fp_1.read())
    fp_1.close()
    # 定義圖片 ID,在 HTML 文本中引用
    msgImage_1.add_header('Content-ID', '<image1>')
    msg.attach(msgImage_1)

    # 附件參數(shù)
    ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)

    # 附件-圖片
#    image = MIMEImage(open(r'C:\Users\Dell\Desktop\regist-cross.jpg', 'rb').read(), _subtype=subtype)
#    image.add_header('Content-Disposition', 'attachment', filename='img.jpg')
#    msg.attach(image)
    
    # 附件-文件
    file = MIMEBase(maintype, subtype)
    file.set_payload(open(r'C:\Users\Dell\Desktop\Day_Report'+'('+time.strftime("%Y-%m-%d") +')'+'.xlsx','rb').read())
    file.add_header('Content-Disposition','attachment',filename='Day_Report'+'_'+time.strftime("%Y-%m-%d")+'.xlsx')
    encoders.encode_base64(file)
    msg.attach(file)

     # 發(fā)送
    smtp = smtplib.SMTP_SSL(host = 'smtp.exmail.qq.com')
    smtp.connect(email_host, 465)
    smtp.login(sender, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

send_mail()
print('----------------success-------------')

PART 4 定時(shí)調(diào)度任務(wù)

import schedule
import time
 
def job():
    import os
    os.system("python ./1_view_python.py")
    os.system("python ./2_picture.py")
    os.system("python ./3_sent_email.py")

    print('----------------success------------------')
 
schedule.every().day.at("13:43").do(job)

# 查詢死循環(huán),每隔10秒查詢
while True:
    schedule.run_pending()
    time.sleep(10)

結(jié)束

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容