当行数量超过1 000 000条记录时,拆分两个或更多工作表

时间:2015-06-22 06:42:35

标签: python django if-statement recursion xlwt

我编写了一个将模型转换为xls文件的函数:

def admin_export_xls(request, model, qs=None):
    mc = apps.get_model(app_label='ecc', model_name=model)
    wb = xlwt.Workbook()
    ws = wb.add_sheet(unicode(mc._meta.verbose_name_plural))

    for i, field in enumerate(mc._meta.get_all_field_names()):
        ws.write(0,i, field)
    if not qs:
        qs = mc.objects.all()

    for ri, row in enumerate(qs):
        for ci, f in enumerate(mc._meta.get_all_field_names()):
            try:
                if unicode(getattr(row, f))[1:51] == 'django.db.models.fields.related.ManyRelatedManager':
                    value = ""
                    for item in getattr(row, f).all():
                        value += unicode(item) + ", "
                    value = value[:-2]
                    ws.write(ri+1, ci, value)
                else:
                    ws.write(ri+1, ci, unicode(getattr(row, f)))
            except:
                try:
                    f += "_set"
                    value = ""
                    for item in getattr(row, f).all():
                        value += unicode(item) + ", "
                    value = value[:-2]
                    ws.write(ri+1, ci, value)
                except:
                    ws.write(ri+1, ci, "")
    fd, fn = tempfile.mkstemp()
    os.close(fd)
    wb.save(fn)
    fh = open(fn, 'rb')
    resp = fh.read()
    fh.close()
    response = HttpResponse(resp, content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=%s.xls' % \
          (unicode(mc._meta.verbose_name_plural),)
    return response

现在我需要编写一个条件,它确定行数是否超过1 000 000然后我们开始写入另一个工作表。

如何在此函数中实现它而不进行递归? 谢谢!

0 个答案:

没有答案