We recently added some reporting functions to an internal tool, including an export-to-excel feature powered by xlwt.
The report generator wrote the reports to a temporary folder, then we used something like the following in a view to download the file:
filedata = open(settings.TEMP_FOLDER_LOCATION + '/' + filename,'r').read()
response = HttpResponse(filedata, mimetype='application/ms-excel')
That worked. Sortof. On some browsers the file was saved without the .xls extension. A little research turned up the Content-disposition header.
Now, all I had to to was add that header to the Django response. Turns out, that's pretty easy. The Django HttpResponse object accepts headers as if it were a dictionary. I broker the above code out into a method I could reuse, and ended up with this:
def tmp_file_response(filename):
filedata = open(settings.TEMP_FOLDER_LOCATION + '/' + filename,'r').read()
response = HttpResponse(filedata, mimetype='application/ms-excel')
response['Content-disposition'] = 'attachment; filename=' + filename
return response
Which does exactly what I wanted.
Posted in
Tech Notes
on February 15, 2010