1,SMTP發送帶excel附件的郵件:
def sendMail(filename, addressee): """ :param content: 發送內容 :param sendStr: 收件人 :return: sendmail """ msg = MIMEMultipart('related') msg["Subject"] = "表格導出" # msg["From"] = "***@qq.com" msg["To"] = addressee thebody = MIMEText(u'正文', 'plain', 'utf-8') msg.attach(thebody) att = MIMEText(open(u'%s.xls' % filename, 'rb').read(), 'base64', 'GB2312')#附件 att['Content-Type'] = 'application/vnd.ms-excel' att['Content-Disposition'] = 'attachment; filename ="%s.xls"' % filename #xlsx格式 # att = MIMEText(open(u'%s.xlsx' % filename, 'rb').read(), 'base64', 'utf-8') # att['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # att['Content-Disposition'] = 'attachment; filename ="%s.xlsx"' % filename msg.attach(att) server = smtplib.SMTP_SSL("smtp.qq.com", 465) server.login("***@qq.com", "***")#第二個參數為郵件配置密鑰 server.sendmail("***@qq.com", addressee, msg.as_string()) server.quit()
2,生成excel發送郵件並下載到本地客戶端:
#views.py def export_to_excel(request): data = [{'a': '1','b':'1'},{'a':'2','b':'2'}] filename = 'export' addressee = '***@***.com' workbook = xlwt.Workbook() sheet = workbook.add_sheet('sheet1', cell_overwrite_ok=True) for i in range(0, len(data[0])): sheet.write(0, i, data[0].keys()[i]) for row in range(1, len(data) + 1): for col in range(0, len(data[0].items())): sheet.write(row, col, u'%s' % data[row - 1].values()[col]) print data[0].keys() workbook.save(r"%s.xls" % filename) sendMail(filename, addressee) sio = StringIO.StringIO() # StringIO用來作為字符串的緩存,有些接口和文件操作一致,代碼可以同時當成文件操作或者StringIO操作。 workbook.save(sio) sio.seek(0) response = HttpResponse(sio.getvalue(),content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=%s.xls' % filename #xlsx文件,出現拓展名的地方都要改為xlsx #response = HttpResponse(sio.getvalue(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') #response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % filename response.write(sio.getvalue()) exist_file = os.path.exists(r"%s.xls" % filename) if exist_file: #生成的文件會在項目文件里存留,所以在下載或者發送之后要刪除 os.remove(r"%s.xls" % filename) return response