1

I have created the csv file through django. I have write the encoded data into that. but when i open this file in excel sheet then the unicode characters not display properly.

I also refer this question Django create CSV file that contains Unicode and can be opened directly with Excel

But didn't get the proper answer. I have tried all the answers, but didn't work any of them.

I write the code as below.

    def exportcsv(request):
        import csv
        producer_list = Producer.objects.filter()
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename=producer.csv'
        writer = csv.writer(response, delimiter=",")
        writer.writerow(codecs.BOM_UTF16_LE)
        writer.writerow(['Produsenter','Type','Land','Region'])
        for cdst in producer_list:
            writer.writerow([cdst.title.encode("UTF-8"),
                            cdst.producer_type.encode("UTF-8"),
                            cdst.country.country.encode("UTF-8"),
                            cdst.region.region.encode("UTF-8")])
        return response

Then the csv file created properly, but the characters in that not encoded properly. The character will be display like "Tokaj Hétszölö".

When i try

writer.writerow([cdst.title.encode("iso-8859-1"),
                            cdst.producer_type.encode("iso-8859-1"),
                            cdst.country.country.encode("iso-8859-1"),
                            cdst.region.region.encode("iso-8859-1")])

Then the data will we added properly also open it excel file properly. But it give error for some characters like 'æ' and ' in the string.

Error: 'latin-1' codec can't encode character u'\u2013' in position 266: ordinal not in range(256)

I also try the below code.

response['Content-Disposition'] = 'attachment; filename=producer.csv'
response.write(u'\ufeff'.encode('utf8'))
writer = csv.writer(response, delimiter=",")

Also try

writer.writerow(codecs.BOM_UTF16_LE)
writer.writerow(str.decode('utf8').encode('utf_16_le'))
Community
  • 1
  • 1
Meenakshi
  • 259
  • 5
  • 19

2 Answers2

0

You should have a look at unicodecsv. It solved similiar troubles for me.

Jingo
  • 3,200
  • 22
  • 29
0

I have resolve above issue. I write the code as below.

writer.writerow([cdst.title.encode("iso-8859-1"),
                 cdst.producer_type.encode("iso-8859-1"),
                 cdst.country.country.encode("iso-8859-1"),
                 cdst.region.region.encode("iso-8859-1")])

using above code i got the error as

Error: 'latin-1' codec can't encode character u'\u2013' in position 266: ordinal not in range(256)

But this error is because of empty string and for '-' character when i pass to encoding. This can be resolved when i set condition before passing the string to encoding and replace the '-' character with '_'.

Meenakshi
  • 259
  • 5
  • 19