On a django site, I want to generate an excel file based on some data in the database.
I'm thinking of using xlwt, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?
I've also found this snippet but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)
You might want to check huDjango which comes fith a function called
serializers.queryset_to_xls()
do convert a queryset into an downloadable Excel Sheet.You can save your XLS file to a StringIO object, which is file-like.
You can return the StringIO object's
getvalue()
in the response. Be sure to add headers to mark it as a downloadable spreadsheet.If your data result doesn't need formulas or exact presentation styles, you can always use CSV. any spreadsheet program would directly read it. I've even seen some webapps that generate CSV but name it as .XSL just to be sure that Excel opens it
***UPDATE: django-excel-templates no longer being maintained, instead try Marmir http://brianray.github.com/mm/
Still in development as I type this but http://code.google.com/p/django-excel-templates/ Django excel templates project aims to do what your asking.
Specifically look at the tests. Here is a simple case:
neat package! i didn't know about this
According to the doc, the
save(filename_or_stream)
method takes either a filename to save on, or a file-like stream to write on.And a Django response object happens to be a file-like stream! so just do
xls.save(response)
. Look the Django docs about generating PDFs with ReportLab to see a similar situation.edit: (adapted from ShawnMilo's comment):
then, from your view function, just create the
xls
object and finish withUse https://bitbucket.org/kmike/django-excel-response