Rename column headers with python DictWriter

484 views
Skip to first unread message

BIJAL MANIAR

unread,
Mar 15, 2019, 4:52:11 AM3/15/19
to Django users


Hi,

Using Python DictWriter can we rename the column names?

Need to rename headers in CSV file so that output looks like. Basically need to rename database fieldnames like emp_name, emp_role to Name,Designation:
Name, Designation
ABC, IT
DEF, Admin

I am using Python DictWriter in django view and below is the snippet:
def export_csv(request):
data = [
{'emp_name': 'ABC', 'emp_role': 'IT'},
{'emp_name': 'DEF', 'emp_role': 'Admin'}
]
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="export.csv"'

fieldnames = ['emp_name', 'emp_role']
writer = csv.DictWriter(response, fieldnames=fieldnames, extrasaction='ignore')
writer.writeheader()
for row in data:
writer.writerow(row)
return response


Thanks,
Bijal

Naeem Sunesara

unread,
Mar 15, 2019, 7:46:14 AM3/15/19
to django...@googlegroups.com
Hey Bijal ,

You can use Python pandas library ..

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3b805ab5-5214-4258-97e0-e7d2388baf21%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages