django+xadmin Excel导出功能

adminx.py

 def to_excel(self, request, queryset):
        path = MEDIA_ROOT + 'download_xls/' + request.user.username
        mkdir_p(MEDIA_ROOT + 'download_xls')
        os.popen('chmod 777 %s' % (MEDIA_ROOT + 'download_xls'))
        mkdir_p(path)
        os.popen('chmod 777 %s' % (path))
        w = Workbook()
        sheet = w.add_sheet(u'入库异常信息表')
        sheet.write(0, 0, u'ID')
        sheet.write(0, 1, u'采购单号')
        sheet.write(0, 2, u'商品SKU')
        sheet.write(0, 3, u'订单状态')
        sheet.write(0, 4, u'异常状态')
        sheet.write(0, 5, u'验货人员')
        sheet.write(0, 6, u'验货时间')
        sheet.write(0, 7, u'入库数量')
        sheet.write(0, 8, u'入库人员')
        sheet.write(0, 9, u'入库时间')
        sheet.write(0, 10, u'仓位')
        sheet.write(0, 11, u'仓库')
        row = 0
        for qs in queryset[:60001]:
            show_Store_StoreName=b_store_log.objects.filter(NID=qs.StoreID)
            for i in show_Store_StoreName:
                row = row + 1
                sheet.write(row, 0, qs.id)
                sheet.write(row, 1, qs.BillNumber)
                sheet.write(row, 2, qs.SKU)
                sheet.write(row, 3, qs.OrderStatus)
                sheet.write(row, 4, qs.Archive)
                sheet.write(row, 5, qs.InspectedMan)
                sheet.write(row, 6, qs.InspectedTime)
                sheet.write(row, 7, qs.InstoreNumber)
                sheet.write(row, 8, qs.InStoreMan)
                sheet.write(row, 9, qs.InStoreTime)
                sheet.write(row, 10, qs.LocationName)
                sheet.write(row, 11, i.StoreName)
        filename = request.user.username + '_' + datetime.now().strftime('%Y%m%d%H%M%S') + '.xls'
        w.save(path + '/' + filename)
        os.popen(r'chmod 777 %s' % (path + '/' + filename))
        # 上传oss对象
        auth = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
        bucket = oss2.Bucket(auth, ENDPOINT, BUCKETNAME_XLS)
        bucket.create_bucket(oss2.BUCKET_ACL_PUBLIC_READ)
        # 删除现有的
        for object_info in oss2.ObjectIterator(bucket, prefix='%s/%s_' % (request.user.username, request.user.username)):
            bucket.delete_object(object_info.key)
        bucket.put_object(u'%s/%s' % (request.user.username, filename), open(path + '/' + filename,'rb'))
        download_url='%s%s.%s/%s/%s' % (PREFIX, BUCKETNAME_XLS, ENDPOINT_OUT, request.user.username, filename)
        try:
            return messages.error(request, u'《《《《《《《《《《《《《《《《《《《《导出成功,点击此处进行下载》》》》》》》》》》》》》》》》》》》》' % (download_url))
        except:
            return HttpResponseRedirect(download_url)
    to_excel.short_description = u'Excel导出(最高6万条)'

你可能感兴趣的:(django+xadmin Excel导出功能)