Excel Spreadsheet Export

 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

  1. Group sequence into rows and columns for a TABLE by davidwtbuxton 2 years, 3 months ago
  2. HTML to text filter by MasonM 4 years, 9 months ago
  3. Reshape list for table, flatten index in nested loops by aquagnu 5 years, 3 months ago
  4. Digg-like pagination by SmileyChris 3 years, 12 months ago
  5. Python Calendar wrapper template tag by dokterbob 4 years ago

Comments

youell (on July 25, 2008):

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?

#

MasonM (on July 26, 2008):

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).

#

phxx (on August 12, 2008):

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?

#

MasonM (on August 13, 2008):
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.

#

phxx (on August 13, 2008):

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.

#

sspross (on October 12, 2010):

i did it with xlwt: http://djangosnippets.org/snippets/2233/

#

(Forgotten your password?)