使用python生成oracle數據報表

#!/usr/bin/env python
#coding:utf-8
# cx_Oracle 用於訪問oracle和導出數據
import cx_Oracle
# xlsxwriter 用於生成xlsx文件
import xlsxwriter
import time
import sys
# 導入郵件模塊
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
 
reload(sys)
sys.setsys.setdefaultencodingdefaultencoding("gbk")     #修改默認編碼爲“gbk”,解決中文編碼問題 不進行設置會出現 UnicodeDecodeError: 'ascii' codec can't decode byte 0xa1 in position 36: ordinal not in range(128)
 
con = cx_Oracle.connect("comm/12345678@orcl")
cursor = con.cursor()
 
#定義SQL腳本 由於腳本包含中文,使用decode('utf-8').encode('gbk') 對其進行轉換
sql ='''
select count 收費金額,
     locate 分中心
from business
'''.decode('utf-8').encode('gbk')
 
query1 = cursor.execute(sql)   #執行查詢
 
title = [i[0] for i in query1.description]
 
date_now=time.strftime("%Y%m%d",time.localtime())
 
#文件名及其路徑
 
report_name='/excel/' + "業務數據".decode('utf-8').encode('gbk') + date_now + '.xlsx'
 
#生成xlsx格式oracle查詢統計報表
 
workbook = xlsxwriter.Workbook(report_name, {'constant_memory': True})
worksheet = workbook.add_worksheet()
print time.ctime()
data = cursor.fetchall()
print time.ctime()
worksheet.write_row(0, 0, title)
for row, row_date in enumerate(data):
    worksheet.write_row(row+1, 0, row_date)
print time.ctime()
cursor.close()
con.close()
workbook.close()
 
#以下代碼實現發送郵件
 
msg = MIMEMultipart()
 
#定義附件名
 
att1_name="業務數據".decode('utf-8').encode('gbk') + date_now + '.xlsx' 
 
#讀入附件,report_name
 
att1 = MIMEText(open(report_name, 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename=%s' % att1_name.encode('gbk')
msg.attach(att1)
 
msg['to'] = '[email protected]'
msg['from'] = '[email protected]'
msg['subject'] = "每週業務數據".decode('utf-8').encode('gbk')
try:
    server = smtplib.SMTP()
    server.connect('mail.126.com')
    server.login('[email protected]','12345678')#
    server.sendmail(msg['from'], msg['to'],msg.as_string())
    server.quit()
    print 'successful.'
except Exception, e:
    print str(e)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章