def export_csv(request):
response = HttpResponse(mimetype = 'text/csv')
response['Content-Disposition'] = 'attachment; filename=exported.csv'
writer = csv.writer(response)
data = [['First-Name','Last-name'],['Foo','baar']]
for entry in data:
writer.writerow(entry)
return response
Above code is written for outputting csv file from django. Problem I am facing is the exported/outputted file’s content are not displaying in different boxes in csv file editor(s). For each entry in data (list) it is getting printed in same box rather it should interpret each entry’s value(First-Name, Last-Name) in different box.
Actual result in csv file:
|First-Name,Last-Name |
|Foor,bar |
Expected:
|First-Name |Last-Name |
|Foo |Baar |
How can I get mechanism by which it will export the file independent on the list size and its contents?
You could set your own dialect for csv.writer with your own custom delimiters etc :
The main cause of the problem with different editors different behaviour – that you should correctly set CSV-delimiter to one you really used – in each editor itself. One more possible reason – is that you don’t use quoting for each CSV-value (that’s quoting=1 in dialect class).
One more thing you could expect, according to your expected output- the same length for each field, filling spaces for the rest – that couldn’t be done through csv module, but you could format your data to the same length for each cell using standard python formats like: