2

I'm developing an application using web2py, and I want to generate a csv file so that the columns becomes rows.

e.g: The file is generated as:

  name    mobile    email    Address
  yyy     yyyyy      yyy     yyyyy

I want the file to be generated as the following design:

name      yyy
mobile    yyyy
email     yyyyyy
Address   yyyy

How can I do this?

I used this code to generate the csv file:

import gluon.contenttype
response.headers['Content-Type'] = \
    gluon.contenttype.contenttype('.csv')
response.headers['Content-disposition'] = 'attachment; filename=members_approaching_renewal_report.csv'\   rows=db().select(db.member.membership_id,db.member.first_name,db.member.middle_name,db.member.last_name,db.member.birthdate,db.member.membership_status,db.member.registration_date,db.member.membership_end_date)
rows.colnames=('Membership Id','First Name','Middle Name','Last Name','Birthday Date','Membership Status','Registration Date','Membership ending Date')
return str(rows)

How should I edit this code to make what I want?

1 Answer 1

6

If your results are in a list of lists called results, and your header titles are in a list called headers you can transpose it like this:

transposed = zip(headers, *results)

Then output as normal, with something like:

import csv
csv_writer = csv.writer(filename)
csv_writer.writerows(transposed)
Sign up to request clarification or add additional context in comments.

4 Comments

i don't use this method to generate by this way deeply when i have records returned from database Thanks in advance
I don't understand. This method should regardless of the source of the records.
i have rows=db().select(db.member.membership_id,db.member.first_name,db.member.middle_name,db.member.last_name,db.member.birthdate,db.member.membership_status,db.member.registration_date,db.member.membership_end_date) rows.colnames=('Membership Id','First Name','Middle Name','Last Name','Birthday Date','Membership Status','Registration Date','Membership ending Date') How can use "rows" to be displayed into csv file?? --> i used gluon method but i cant transpose the file if you know another methode could you please tell me. Thanks in advance
I don't know what gluon is. If you can get your results into a list of lists, then you can use my method. If you can't, could you tell me what format it is?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.