StringIO 生成的包含 BOM 的 csv 文件

use*_*629 5 python csv encoding python-3.x

我正在尝试生成在 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
Run Code Online (Sandbox Code Playgroud)

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

我还尝试了以下方法:

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

没有运气

我该怎么做才能utf-8-sig使用 BOM正确编码输出文件,以便 Excel 打开文件并正确显示多字节 unicode 字符?

geo*_*xsh 7

HttpResponse接受bytes

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

或者让 Django 进行编码:

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