python导出数据到excel
1,SMTP发送带excel附件的邮件:
def sendMail(filename, addressee):
"""
:param content: 发送内容
:param sendStr: 收件⼈
:return: sendmail
"""
getsavefilenamemsg = MIMEMultipart('related')
msg["Subject"] = "表格导出"
# msg["From"] = "***@qq"
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", 465)
server.login("***@qq", "***")#第⼆个参数为邮件配置密钥
server.sendmail("***@qq", 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 = '***@***'
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 = value(),content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=%s.xls' % filename
#xlsx⽂件,出现拓展名的地⽅都要改为xlsx
#response = value(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
#response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % filename
response.value())
exist_file = ists(r"%s.xls" % filename)
if exist_file: #⽣成的⽂件会在项⽬⽂件⾥存留,所以在下载或者发送之后要删除
return response
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论