StringIO生成的csv文件,其中包含BOM

时间:2017-10-09 14:47:46

标签: python python-3.x csv encoding

我尝试生成在Excel中正确打开的CSV,但使用的是StringIO而不是文件。

  output = StringIO("\xef\xbb\xbf") # Tried just writing a BOM here, didn't work
  fieldnames = ['id', 'value']
  writer = csv.DictWriter(output, fieldnames, dialect='excel')
  writer.writeheader()
  for d in Data.objects.all():
        writer.writerow({
          'id': d.id,
          'value': d.value
        })
  response = HttpResponse(output.getvalue(), content_type='text/csv')
  response['Content-Disposition'] = 'attachment; filename=data.csv')
  return response

这是Django视图的一部分,所以我真的不愿意为此倾销临时文件。

我还尝试过以下方法:

response = HttpResponse(output.getvalue().encode('utf-8').decode('utf-8-sig'), content_type='text/csv')

没有运气

如何使用BOM在utf-8-sig中正确编码输出文件,以便Excel打开文件并正确显示多字节unicode字符?

1 个答案:

答案 0 :(得分:4)

HttpResponse接受bytes

output = StringIO()
...
response = HttpResponse(output.getvalue().encode('utf-8-sig'), content_type='text/csv')

或让Django进行编码:

response = HttpResponse(output.getvalue(), content_type='text/csv; charset=utf-8-sig')