Python-Django utf-8 csv.writer

Ara*_*ash 0 python csv django utf-8

即时通讯使用python csv库将我的模型导出到Django中的csv文件中。代码是这样的:

import csv
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response
Run Code Online (Sandbox Code Playgroud)

我的问题: 在我的数据库中,我有一些波斯字符,只能使用utf-8编码格式,因此当我在excel中打开生成的csv文件时,波斯字符无法正确显示。

Ara*_*ash 6

我在某些情况下尝试编码('UTF-8')解决方案,但Microsoft excel中的结果不可读,它显示b'\ xd8 \ xb1 \ xdb \ x8c \ xd8'。但是我找到了以excel可读格式显示CSV的正确方法。

import csv
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    response.write(u'\ufeff'.encode('utf8'))
    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response
Run Code Online (Sandbox Code Playgroud)

只需将response.write(u'\ ufeff'.encode('utf8'))添加到代码中


小智 5

只需添加此新行代码:

response.write(codecs.BOM_UTF8)
Run Code Online (Sandbox Code Playgroud)

在这一行之后:

 response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
Run Code Online (Sandbox Code Playgroud)