开发者

Use pyExcelerator to generate dynamic Excel file with Django. Ensure unique temporary filename

I'd like to generate a dynamic Excel file on request from Django. The library pyExcelerator does this, but I ha开发者_如何学Pythonven'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?


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/ms-excel")
    response['Content-Disposition'] = 'attachment; filename="foo.xls"'
    wb = xlwt.Workbook()
    wb.save(response)
    return response


Why can you not use the tempfile module?

How about:

import tempfile
fd, filename = tempfile.mkstemp()
fd.close()
workbook.save(filename)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜