This is an example of a view that returns an Excel spreadsheet; the last ~7 lines are the relevant ones. It relies on Excel's ability to automatically import HTML (see http://support.microsoft.com/kb/165499 for more info). The spreadsheet.html template is just has one big <table>
tag with all the data as table cells (no <html>
or other surrounding tags are necessary).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | def generate_spreadsheet(request):
"""
Generates an Excel spreadsheet for review by a staff member.
"""
election = Election.objects.latest()
ballots = election.ballots.all()
ballots = SortedDict([(b, b.candidates.all()) for b in ballots])
# Flatten candidate list after converting QuerySets into lists
candidates = sum(map(list, ballots.values()), [])
votes = [(v, v.get_points_for_candidates(candidates))
for v in election.votes.all()]
response = render_to_response("spreadsheet.html", {
'ballots': ballots.items(),
'votes': votes,
})
filename = "election%s.xls" % (election.year_num)
response['Content-Disposition'] = 'attachment; filename='+filename
response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-8'
return response
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
I like it. I've used this same approach in ASP for many years. Do you know if OpenOffice can do the same trick as Excel?
#
Yep. I just tried it in OpenOffice 2.4 and it worked fine. It took a pretty long time to import on my system, but that's probably because the election.xls spreadsheet that the above view returns is huge (>200KB).
#
Sorry, but i don't get where the excel file is generated. If I'm right it just attaches a file to the html response?
#
There's no such thing as an "HTML response" in Django; you must mean "HTTP response". The HTTP response this view generates contains an HTML file marked as an attachment with a MIME type of "vnd.ms-excel". Excel recognizes HTML and auto-imports it, as I said in the description.
#
ok, I thought it's just a reponse with html content but a different mimetype. And as you explained: It's just that. But that your spreadsheet app imports html is cool =)
Thanks for making things clear.
#
Please login first before commenting.