解码utf-8中的CSV文件(Django +熊猫)

时间:2019-10-29 15:03:37

标签: python django pandas

我的代码生成一个csv文件,并将其返回到浏览器。下载文件后,所有俄语单词都看起来像:Абакан...编码似乎无效。请告诉我,我该如何解决这个问题?

dataCsv = data.to_csv(sep=';', header='True', decimal=',', encoding='utf-8')
response = HttpResponse(dataCsv, content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename=data.csv'

return response

3 个答案:

答案 0 :(得分:0)

我认为您应该为俄语使用“ cp869编解码器”

查看链接以获取更多详细信息: https://docs.python.org/2.4/lib/standard-encodings.html

答案 1 :(得分:0)

我最近在使用UTF-8和CSV时遇到问题,经过大量搜索后找到了解决方法。我想不起来要相信原始作品,但我要做的是添加:

    response.write(u'\ufeff'.encode('utf8'))

设置响应后。因此,您将拥有:

response = HttpResponse(dataCsv, content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename=data.csv'
response.write(u'\ufeff'.encode('utf8'))

return response

据我了解,这告诉Excel“这是UTF-8编码的文件”。

答案 2 :(得分:0)

在我的设置文件中,插入

DEFAULT_CHARSET = 'cp1251'

观看次数:

dataCsv = data.to_csv(sep=';', header='True', decimal=',', encoding='cp1251')
response = HttpResponse(dataCsv, content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename=data.csv'

return response
相关问题