Excel中的Django csv输出
嗨,我有一个简单的视图,它返回一个查询集的csv文件,该查询集是使用utf-8编码从mysql数据库生成的:Excel中的Django csv输出,django,csv,utf-8,Django,Csv,Utf 8,嗨,我有一个简单的视图,它返回一个查询集的csv文件,该查询集是使用utf-8编码从mysql数据库生成的: def export_csv(request): ... response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=search_results.csv' writer = csv.writer(response,
def export_csv(request):
...
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=search_results.csv'
writer = csv.writer(response, dialect=csv.excel)
for item in query_set:
writer.writerow(smart_str(item))
return response
return render(request, 'search_results.html', context)
作为一个CSV文件,它可以很好地工作,并且可以在文本编辑器、LibreOffice等中毫无问题地打开
但是,我需要提供一个文件,它可以在Windows中的MS Excel中无错误地打开。如果查询集中有带有拉丁字符的字符串,如“Española”,则Excel中的输出为“EspaÔ±ola”
我试过了,但没用。我也知道,但我很好奇,是否有一种方法可以使用我目前使用的CSV方法来纠正输出
非常感谢您的帮助。似乎没有一个统一的解决方案适用于所有版本的Excel
还有一个。您可以尝试一下
python unicodesv
。它取代了pythoncsv
模块,该模块不能很好地处理Unicode
import unicodecsv as csv
我发现Excel要正确打开unicode csv文件需要做3件事:
import codecs
...
def export_csv(request):
...
response = HttpResponse(content_type='text/csv', charset='utf-16-le')
response['Content-Disposition'] = 'attachment; filename=search_results.csv'
response.write(codecs.BOM_UTF16_LE)
writer = csv.writer(response, dialect='excel-tab')
for item in query_set:
writer.writerow(smart_str(item))
return response
我尝试了几种不同的编码。cp1250和其他代码一样产生以下错误:
'ascii'编解码器无法解码第4位的字节0xc3:序号不在范围(128)
您可以将结果(2行)呈现给变量并将其发布到此处以便我可以尝试吗?这是一个简化的´。前两行的值列表:[(u'Abutilon depauperatum',u'Espa\xf1ola'),(u'Abutilon depaupertum',u'Espa\xf1ola')]
哪一个是您的windows代码页cp1252?导出到utf-8并使用iconv:iconv-f utf-8-t cp1252 a.csv>b.csv
抱歉,您必须为我解释更多。