Get the App
SLTechnology News&Howtos  ›  Database  › 

Using python to generate oracle data report

Shulou Source: shulou.com Published: 2022-06-01 15:50:03 10月26日 Update

#! / usr/bin/env python#coding:utf-8# cx_Oracle is used to access oracle and export data import cx_Oracle# xlsxwriter is used to generate xlsx files import xlsxwriterimport timeimport sys# import mail module from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport smtplib reload (sys) sys.setsys.setdefaultencodingdefaultencoding ("gbk") # modify the default code to "gbk" Solve the Chinese coding problem without setting up 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 () # define the SQL script because the script contains text Convert it using decode ('utf-8'). Encode (' gbk') to convert sql = 'select count fee amount, locate branch center from business'''.decode (' utf-8'). Encode ('gbk') query1 = cursor.execute (sql) # execute query title = [I [0] for i in query1.description] date_now=time.strftime ("% Y%m%d" Time.localtime () # File name and its path report_name='/excel/' + "Business data" .decode ('utf-8'). Encode (' gbk') + date_now + '.xlsx' # generate xlsx format oracle query statistics report 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 () # the following code implements sending email msg = MIMEMultipart () # defines the attachment name att1_name= "business data" .decode ('utf-8'). Encode (' gbk') + date_now + '.xlsx' # read the attachment 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'] = 'boss@126.com'msg [' from'] = 'report@126.com'msg [' subject'] = "Weekly Business data" .decode ('utf-8'). Encode (' gbk') try: server = smtplib.SMTP () server.connect ('mail.126.com') server.login (' report@126.com') '12345678') # server.sendmail (msg ['from'], msg [' to'], msg.as_string () server.quit () print 'successful.'except Exception, e: print str (e)

Tags: Data business generation file code script mail attachment Chinese query report code sub-center file name format module statistical report path amount question Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology vpn Huawei Linux MariaDB