python 을 사용 하여 Oacle 데이터 보고 서 를 생 성 합 니 다.

#!/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"] = 'p_w_upload; 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)

좋은 웹페이지 즐겨찾기