7

I'm trying to import to cvs, but I get this error

UnicodeEncodeError at /brokers/csv/'ascii' codec can't encode character u'\u2013' in position 9: ordinal not in range(128)

Unicode error hint

The string that could not be encoded/decoded was: ) 758–9800

I have tried .encode, unicode(), etc and nothing works, I don't know if I need a library or something else, 'cause I have the same code in other machine and is working fine.

 def exportar_a_csv_brokers(request):
     #Fecha actual
     hoy = datetime.now().date()
     #Creado el:
     creado_hoy = hoy.strftime("%m/%d/%Y")
     response = HttpResponse(mimetype='text/csv')
     response['Content-Disposition'] = 'attachment;filename=
     "Reporte de Brokers ' +  creado_hoy + '.csv"'
     response['Content-Type'] = 'text/csv; charset=utf-8'
     response.write("\xEF\xBB\xBF")

     writer = csv.writer(response)
     brokers = Broker.objects.all()
     writer.writerow(['Creado el:             ' + creado_hoy + ' '])
     writer.writerow([''])
     writer.writerow(
    ['Apellido Paterno', 'Nombre', '# Broker', '# Licencia de Seguro', 'ID Federal',  'Nombre Agencia', 'Teléfono',
     'Correo Electrónico', 'Fax', 'Calle', '# Interior', 'Colonia', 'Código Postal', 'Estado', 'Ciudad'])

for broker in brokers:
    #Imprimiendo resultados
    writer.writerow([broker.ap_paterno, broker.nombre, broker.no_broker,
                     broker.no_licencia_seguro, broker.id_federal, broker.nombre_agencia, broker.telefono,
                     broker.correo_electronico, broker.fax,
                     broker.calle, broker.no_interior, broker.colonia, broker.codigo_postal, broker.estado,
                     broker.ciudad])
return response
1

2 Answers 2

11

I'm guessing your using python 2.x?

if so try using .encode('utf-8') on your string when writing.

4

Are you using lib cStringIO? I ran into a similar problem after replacing StringIO with cStringIO. Going back to StringIO was the solution.

Furthermore, you can try using

from __future__ import unicode_literals

as the first line of your code.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.