Split on two and more worksheets when lines amount exceeds 1 000 000 records

55 views Asked by At

I wrote a function which converts models to xls files:

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

Now I need to write a conditional, which determines if amount of lines is more than 1 000 000 then we starting write to another worksheet.

How to implement it in this function with no recursion? Thank you!

0

There are 0 answers