需求背景
每日导出一份会员信息,并以excel形式发送给相关人员,考虑到数据的量,进行了压缩处理
脚本内容
#!/usr/bin/env python
#-*- coding: utf8 -*-
import MySQLdb
import xlsxwriter
import zipfile
import os
import pdb
shell_path = '/mail_centor/Daily_Show/'
xlsx_name = 'crowd_member.xlsx'
xlsx_sheet = 'phones'
print "邮件路径 %s" % shell_path
print "表格名称 %s" % xlsx_name
print "工作区名称 %s" % xlsx_sheet
db_host = "xx.xx.xx.xx"
db_user = "mysql_user"
db_pass = "mysql_pass"
db_dbnm = "mysql_dbname"
print "进入邮件目录 %s" % shell_path
os.chdir(shell_path)
out_excel = xlsxwriter.Workbook(xlsx_name)
out_sheet = out_excel.add_worksheet(xlsx_sheet)
bold = out_excel.add_format({'bold': True})
print "执行数据库脚本"
show_conn = MySQLdb.Connect(db_host,db_user,db_pass,db_dbnm)
show_cursor = show_conn.cursor()
get_phones = """SELECT
b.id, b.cell_phone
FROM
T1 a
INNER JOIN
T2 c ON c.id = a.show_id AND c.state IN (1 , 2)
INNER JOIN
T3 b ON a.member_id = b.id
AND a.create_time BETWEEN ADDDATE(CURDATE(), - 1) AND CURDATE()
WHERE
a.state = 0"""
show_cursor.execute(get_phones)
titles = show_cursor.description
phones = show_cursor.fetchall()
print "将脚本写入到excel"
for column in range(0,len(titles)):
out_sheet.write(0,column,titles[column][0],bold)
for data_1 in range(1,len(phones)+1):
for data_2 in range(0,len(titles)):
out_sheet.write(data_1,data_2, u'%s' % phones[ data_1-1 ][data_2])
show_cursor.close()
show_conn.close()
out_excel.close()
print "将excel打包成zip文件"
to_file = 'crowd_member.zip'
z_new = zipfile.ZipFile(to_file,'w',zipfile.ZIP_DEFLATED)
z_new.write(xlsx_name)
z_new.close()