I need to provide an excel formatted data from django's database to visitors.
The only way I can think of is with these steps:
- Extract data from database.
- Wrap it with
Workbook
object fromopenpyxl
. - Save it somewhere temporarily.
- Read it again as 'rb'.
- return view with excel's mime type.
- Delete excel file on disk. (It's useless now right?)
That should do it. But, I think there's another better way to do this. I mean
maybe there's a way to return openpyxl
object as HttpResponse
directly
without intermediate file medium.
So, my question here is: is it possible to return openpyxl
's Worbook
object? (I'm new with openpyxl
)
this worked for me
You don't actually need to save the data anywhere on disk; openpyxl has a way to do this, although it's not very well documented. A long while back, I created something like this using xlwt, but I recently also built something similar in the Falcon framework, using openpyxl.
Putting these two together, your code would look something along the lines of:
If you are generating larger files, I would recommend looking into using StreamingHttpResponse, but I believe this will at least get you going.
This is just an off-the-cuff snippet based on a merge of the two project I worked on, so it may not be exactly correct. It should be pretty close though. The output in Falcon looked like:
UPDATE: This is now much easier, as I did a complete rewrite of my old
django-excel-response
library, using openpyxl! It can now be found here: https://github.com/tarkatronic/django-excel-responseYou can install it with
pip install django-excel-response
, and start using it as an alternative to Django'sHttpResponse
! There is minimal documentation included, and improvements/suggestions are welcome. :)