2012-10-19 58 views
1

我已经通过django创建了csv文件。我已将编码的数据写入该数据。但是当我在Excel表格中打开此文件时,unicode字符无法正确显示。使用django创建csv文件并直接打开到Excel

我也提到了这个问题 Django create CSV file that contains Unicode and can be opened directly with Excel

但没有得到正确的答案。我已经尝试了所有的答案,但是没有解决任何问题。

我写下如下代码。

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 

然后csv文件正确创建,但在那个字符不正确编码。 角色将显示为“TokajHÃtszölö”。

当我尝试

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")]) 

然后数据我们增加也正常打开Excel文件正确。 但是它给字符串中的'æ'和''等字符提供了错误。

错误:拉丁-1'编解码器无法编码的字符U“\ u2013”​​在266位置:顺序不在范围内(256)

我也尝试下面的代码。

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

也可以尝试

writer.writerow(codecs.BOM_UTF16_LE) 
writer.writerow(str.decode('utf8').encode('utf_16_le')) 
+0

W虽然这不是一个真正的答案,你应该尝试tablib,它允许导出xls。 – bmihelac

回答

0

我已经解决了上述问题。我编写代码如下。

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")]) 

使用上述代码我得到了误差作为

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

但这错误是因为空字符串的和“ - ”字符时,我传递给编码。当我在将字符串传递给编码之前设置条件并用'_'替换' - '字符时,可以解决这个问题。

0

你应该看看unicodecsv。它为我解决了类似的问题。

+0

我已经使用这个。但同样的回应。 – Meenakshi

相关问题