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