UnicodeEncodeError on csv export

180 views
Skip to first unread message

andreas schmid

unread,
Aug 20, 2009, 6:06:57 AM8/20/09
to django...@googlegroups.com
hi,

i successfully made a csv export view for a queryset but i have the
problem with some characters...
how can i encode the queryset passed to the csv writer to solve my problem?

#my csvexport.py

import csv
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

from myapp.models import Project

@login_required
def projects_csv(request):

response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment;
filename=Projects.csv'

csv_data = Project.objects.all()

writer = csv.writer(response)
writer.writerow(['title' ,'area' , 'type', 'axis','beneficiary',
'description', 'budget', 'already paid
amount ',
'length', 'financing' ,
'total_amount_to_finance', 'percentage_to_pay' ,
'restamountto_pay', 'security', 'date'])
for project in csv_data:
writer.writerow([ project.title , project.area ,
project.type, project.axis,project.beneficiary,
project.description, project.budget,
project.already_paid_amount,
project.length, project.financing,
project.total_amount_to_finance, project.percentage_to_pay_by_tis ,
project.restamount_to_pay,
project.security, project.pub_date ])
return response

thank you...


mettwoch

unread,
Aug 20, 2009, 6:15:13 AM8/20/09
to Django users
I ran into the same problem and I found in the Python documentation
that the csv module has some Unicode issues ...

http://docs.python.org/library/csv.html?highlight=csv#module-csv

... with an attempt to getting around it with a wrapper ...

http://docs.python.org/library/csv.html?highlight=csv#csv-examples

..., but I didn't try it myself (other priorities). If You give it a
try, please provide feedback if it works, otherwise You can always
fallback to constructing the csv 'by hand' in a template as proposed
in the Django docs

http://docs.djangoproject.com/en/dev/howto/outputting-csv/

Kindly Yours
Marc

andreas schmid

unread,
Aug 20, 2009, 8:00:46 AM8/20/09
to django...@googlegroups.com
i used the template method to get it working because it was the faster
and easier way.... thank you for pointing me there!

if someone knows how to make it work directly with the python csv i
would be interested to see how it should be implemented!

David De La Harpe Golden

unread,
Aug 20, 2009, 8:18:15 AM8/20/09
to django...@googlegroups.com
andreas schmid wrote:
> hi,
>
> i successfully made a csv export view for a queryset but i have the
> problem with some characters...
> how can i encode the queryset passed to the csv writer to solve my problem?
>

FWIW, I just did the following:

for line in lines:
writer.writerow(
[unicode(s).encode("utf-8") for s in (
line.field1,
line.field2,
)
]
)


Reply all
Reply to author
Forward
0 new messages