Streams a list as a CSV. Useful if you need to return a database query in a way which the user can immediately import to a spreadsheet.
Here is an example use in a controller:
def view_payment_details(): form=FORM('Date 1:', INPUT(_name='date1',_class='date',_size=10,requires=IS_DATE(format='%Y-%m-%d',error_message='must be YYYY-MM-DD')),'Date 2:', INPUT(_name='date2',_class='date',requires=IS_DATE(format='%Y-%m-%d',error_message='must be YYYY-MM-DD')), INPUT(_type='submit'),keepvalues=True) accpac_orders = {} if form.accepts(request,session): date1_ymd = request.vars.date1 date2_ymd = request.vars.date2 #next line gets a list of records as a result of a database query accpac_orders = reconcile.get_accpac_orders(date1_ymd, date2_ymd) field_names = ('Order Nbr','Invoice Nbr' ,'Location','Reference','Order Date','Invoice Date','Amount Paid','Amount Invoiced') response.view='generic_list.csv' return dict(filename='accpac_payment_details.csv', csvdata=accpac_orders,field_names=field_names) return dict(form=form,date1=date1_ymd)
Below is the contents of views/generic_list.csv
{{ ### # Stream a CSV # for this to work the controller must return # # dict(filename=...,csvdata=...,field_names=...) # # filename is the suggested name to save the file as # csvdata is the list to output # field_names is a list of column headers ### try: thefile = filename except: thefile = 'export.csv' pass # the try block is commented out because it obscures errors that # may be interesting while debugging #try: import cStringIO import csv stream=cStringIO.StringIO() #field_names = ('Order Nbr','Invoice','Location','Payment ID','Date1','Date2','Amount1','Amount2') csv_writer = csv.writer(stream) csv_writer.writerow(field_names) for row in csvdata: csv_writer.writerow(row) pass response.headers['Content-Type']='application/vnd.ms-excel' response.headers['Content-disposition']='attachment; filename=' +thefile response.write(stream.getvalue(), escape=False) #except: # raise HTTP(405,'no css') }}
Comments (0)