[Answer]-Export a template information into an Excel and then download it in django

1👍

I have following code in similar place:

“place a bottom” – is link, like this:

<a href="/some/path/report"></a>

in urls.py:

...
url(r'^/some/path/report$', file_load_view),
...

in view.py

from StringIO import StringIO
from csv import DictWriter

@require_http_methods(["GET"])
def file_load_view(self, request):
    f = StringIO()
    writer = DictWriter(f, ["Tipo de Factura", "Descripcion", "Precio", "Subtotal", "total", "paid"])
    writer.writeheader()
    report_line = {
        "Tipo de Factura": fact.tipo_Factura,
        "Descripcion": fact.descripcion,
        ...
    }
    writer.writerow(report_line)
    report = f.getvalue()
    resp = HttpResponse(report, mimetype="application/octet-stream")
    resp["Content-Disposition"] = "attachment; filename='{}'".format("report.csv")
    return resp

As result user load csv file (it is almost the same as ‘exel’) contains report like this:

Tipo de Factura,Descripcion,Precio,Subtotal,total,paid
1,2,3,4,5,6 

If you already have report in file on your disk report may equal:

...
fd = open("report/path/report.csv")
report = fd.read()
...
👤sheh

Leave a comment