我正在尝试输出一个用户可以用 Excel 打开的 CSV 文件。我已经用 UTF-8 编码了所有字符串,但是当我用 Excel 打开文件时,我看到了乱码。只有在将文件转换为带 BOM 的 UTF-8(在 Windows 上使用 notepad++)后,我才能正确显示内容。
我正在遵循这个模式docs https://docs.djangoproject.com/en/1.8/howto/outputting-csv/#using-the-python-csv-library:
def render_to_csv(self, request, qs):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="test.csv"'
writer = csv.writer(response, delimiter=',')
for row in qs.values_list(*self.fields_to_export):
writer.writerow([unicode(v).encode('utf-8') if v is not None else '' for v in row])
return response
BOM 在这一切中扮演什么角色?
顺便说一句,有类似的问题 https://stackoverflow.com/questions/10846133/django-create-csv-file-that-contains-unicode-and-can-be-opened-directly-with-exc就这样,但不幸的是他们都没有得到答复。
EDIT
在 @Alastair McCormack 的基础上,我最终在文件开头显式添加了 BOM 字符。唯一的区别是我使用了编解码器包而不是对字节进行硬编码。感觉很尴尬,但确实有效!
import codecs
def render_to_csv(self, request, qs):
...
response.write(codecs.BOM_UTF8)
...
return response
在写入数据之前将 UTF-8 BOM 添加到响应对象:
def render_to_csv(self, request, qs):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="test.csv"'
# BOM
response.write("\xEF\xBB\xBF")
writer = csv.writer(response, delimiter=',')
…
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)