export table to csv

680 views
Skip to first unread message

Yebach

unread,
Jan 21, 2015, 4:24:36 PM1/21/15
to web...@googlegroups.com
Hello

I am trying to create a one button click export to csv, so if a user click he gets a download popup without redirect to new page

my controller (script.py)

@auth.requires_login()
def excelExport():
import csv
import cStringIO
scriptId = request.args[0]
rows = db(db.result.r_id_script == scriptId).select(db.result.r_item1_name, db.result.r_date, db.result.r_time_start,db.result.r_time_end)
s = cStringIO.StringIO()
rows.export_to_csv_file(s, quoting=csv.QUOTE_ALL)
return s.getvalue()

and my view in views/script/view.html

  {{ if auth.is_logged_in():}}
        {{=A(T('Export EXCEL'), _class='btn btn-primary', callback=URL('script','excelExport',  args = request.args[0]))}}
    {{pass}}

Function is called but what am I missing to get a download window for file so user can save it as and where he wishes?

and one more question. Is there a way to name column headers in csv?

thank you




Dave S

unread,
Jan 21, 2015, 8:17:49 PM1/21/15
to web...@googlegroups.com


On Wednesday, January 21, 2015 at 1:24:36 PM UTC-8, Yebach wrote:
 
and one more question. Is there a way to name column headers in csv?


Exporting, that seems to be done for you.

<URL:http://web2py.com/books/default/chapter/29/06/the-database-abstraction-layer?search=import+csv#CSV--one-Table-at-a-time->
mentions that the import function looks for column names in the CSV header.
In the appadmin database interface, I update one of my tables with a CSV file all the time, and the first line of my file is
id,colname1,colname2, etc

/dps




Dave S

unread,
Jan 21, 2015, 9:53:20 PM1/21/15
to web...@googlegroups.com
A quick look at dal.py suggests that the importer doesn't support comment lines.

/dps
 

Yebach

unread,
Jan 22, 2015, 3:11:20 AM1/22/15
to web...@googlegroups.com
I managed to solve the issue with the following code

def csvExport():
        scriptId = request.args[0]
#rows = db(query,ignore_common_filters=True).select()
rows = db(db.result.r_id_script == scriptId).select(db.result.r_item1_name, db.result.r_date, db.result.r_time_start,db.result.r_time_end)
from gluon.contenttype import contenttype
response.headers['Content-Type'] = contenttype('.csv')
response.headers['Content-disposition'] = 'attachment; filename=export_%s.csv' % (scriptId)
import csv, cStringIO
s = cStringIO.StringIO()
rows.export_to_csv_file(s, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
return s.getvalue()

andbutton in my view.html

  {{=A(T('CSV export'), _class='btn btn-primary', _href=URL('script','csvExport',  args = request.args[0]))}}

instead of callback i used _href

it works :)
Reply all
Reply to author
Forward
0 new messages