25 Nov 2007

Exporting a csv file with web.py

This is how you export a csv file and get the browser to recognize that its a csv file and popups the download window with web.py. Lets say we have a database with a table called users and you want to create a csv file that contains all the users with their names and id’s here is how you do it.


1 class export:
2     def GET(self):
3         i = web.input()
4
5
6         users = web.select(’users’, vars=locals())
7
8         csv = []
9         csv.append(”id,name\n”)
10        for user in users:
11             row = []
12             row.append(user.id)
13             row.append(user.name)
14
15            csv.append(”,”.join(row))
16         #writer.writerow(row)
17
18         #f.close()
19
20     web.header(’Content-Type’,’text/csv’)
21     web.header(’Content-disposition’, ‘attachment; filename=export.csv’)
22     print “”.join(csv)
23     return




I export the csv file in a GET method of a class called export which i map in the urls list to ‘/export’,‘export’

A quick breakdown, do a database query and iterate over the IterBetter object create a row and appending a comma seperated string to the csv list. Then at the end you send the appropirate HTTP headers , the first telling the type of the file and the second setting the filename and extension.

Anyway you can download this code from http://bulkanix.pastebin.com/f1f567ea0