views:

304

answers:

2

I'd like to generate a dynamic Excel file on request from Django. The library pyExcelerator does this, but I haven't found any way to use the contents of the Excel file without generating a server-side temporary Excel file, reading it, using its contents and deleting it.

The problem is that pyExcelerator only way to extract the contents of the Excel file is saving it via:

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

And then read the temporary file contents. I can't use the standard library "tempfile" because it doesn't accept a file, just a filename. How can I ensure that the filename is unique and that the file is deleted once it has been used?

+3  A: 

Why can you not use the tempfile module?

How about:

import tempfile
fd, filename = tempfile.mkstemp()
fd.close()
workbook.save(filename)
codeape
+1. Just remember to delete the file after using it; according to the fine manual: "Caller is responsible for deleting the file when done with it."
ema
+5  A: 

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

from django.http import HttpResponse
import xlwt

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