Use pyExcelerator to create a dynamic Excel file using Django. Providing a unique temporary file name

I want to create a dynamic Excel file as requested from Django. The pyExcelerator library does this, but I did not find any way to use the contents of the Excel file without creating a temporary Excel file on the server side, reading it, using its contents and deleting it.

The problem is that pyExcelerator only for extracting the contents of an Excel file saves it via:

workbook = pyExcelerator.Workbook()
workbook.save("tmp_filename")

And then read the contents of the temporary file. I cannot use the standard tempfile file because it does not accept the file, just the file name. How can I make sure that the file name is unique and that the file is deleted after using it?

+3
source share
2 answers

pyExcelerator is not supported, but it has fork, xlwt , which is supported and has more features, including allowing you to save any file-like object. This includes saving directly to Django HttpResponse:

from django.http import HttpResponse
import xlwt

def my_view(request):
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename="foo.xls"'
    wb = xlwt.Workbook()
    wb.save(response)
    return response
+11
source

Why can't you use the module tempfile?

What about:

import tempfile
fd, filename = tempfile.mkstemp()
fd.close()
workbook.save(filename)
+3
source

Source: https://habr.com/ru/post/1725379/


All Articles