Navigate back to the homepage

Exporting a csv file with web.py

Bulkan Evcimen
November 25th, 2007 · 1 min read

Photo by Mika Baumeister on Unsplash

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.

1class export:
2 def GET(self):
3 i = web.input()
4 users = web.select(’users’, vars=locals())
5 csv = []
6 csv.append(id,name\n“)
7 for user in users:
8 row = []
9 row.append(user.id)
10 row.append(user.name)
11 csv.append(,.join(row))
12
13 web.header(’Content-Type’,’text/csv‘)
14 web.header(’Content-disposition’, ’attachment; filename=export.csv‘)
15 print "".join(csv)
16 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.

More articles from Bulkan

Using Vuejs with Parcel and p5.js

Photo created by grid-art.bulkan.dev This is part two of a two part series. In part one I showed you how you can setup a project using…

August 23rd, 2020 · 1 min read

Using Parcel, TypeScript with p5.js

Photo created by grid-art.bulkan.dev This is part one of a two part series and you can read Part two . p5.js is already great at being…

August 10th, 2020 · 2 min read
© 2007–2020 Bulkan
Link to $https://twitter.com/bulkanevcimenLink to $https://github.com/bulkanLink to $https://instagram.com/bulkan.evcimen