zoukankan      html  css  js  c++  java
  • python导出数据到excel

    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
  • 相关阅读:
    02 Filter过滤器
    Vue入门
    Git教程
    Markdown 常用语言关键字
    王爽《汇编语言》(第三版)实验16解析
    王爽《汇编语言》(第三版)实验15解析
    王爽《汇编语言》(第三版)实验14解析
    王爽《汇编语言》(第三版)实验13解析
    王爽《汇编语言》(第三版)实验12解析
    王爽《汇编语言》(第三版)实验11解析
  • 原文地址:https://www.cnblogs.com/youleng/p/8657902.html
Copyright © 2011-2022 走看看