从django返回以BOM表以UTF-8编码的csv [英] Return a csv encoded in UTF-8 with BOM from django

查看:192
本文介绍了从django返回以BOM表以UTF-8编码的csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试输出用户可以使用excel打开的CSV文件.我已经用UTF-8编码了所有字符串,但是当我用excel打开文件时,我看到了颤动.仅在使用BOM将文件转换为UTF-8后(在Windows上使用notepad ++),我才能够正确显示内容.

I'm trying to output a CSV file that the user could open with excel. I've encoded all string in UTF-8 but when I opened the file with excel I see jibrish. Only after converting the file to UTF-8 with BOM (using notepad++ on windows) I was able to display the content properly.

我正在从

物料清单在哪里适合所有这些?

Where does to BOM fit into all of this ?

顺便说一句,有

BTW, There are similar questions on SO but unfortunately non of them are answered.

编辑

基于@Alastair McCormack,我最终在文件的开头明确添加了BOM字符.唯一的不同是,我使用了编解码器包,而不是对字节进行硬编码.感觉很尴尬,但能解决问题!

building on @Alastair McCormack, I ended up explicitly adding the BOM characters at the begining of the file. Only difference is i used the codecs package instead of hard coding the bytes. Feels awkward but does the trick !

import codecs

def render_to_csv(self, request, qs): 
  ... 
  response.write(codecs.BOM_UTF8)
  ...
  return response

推荐答案

在写入数据之前,将UTF-8 BOM添加到响应对象:

Add the UTF-8 BOM to the response object before you write your data:

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=',')
  …

这篇关于从django返回以BOM表以UTF-8编码的csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆