Django导出excel中文乱码解决方案

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

如果遇到中文,会产生乱码

解决方法:在response里写入BOM  response.write(codecs.BOM_UTF8):

import csv,codecs
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.write(codecs.BOM_UTF8)
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

*****************************

附上非Django情况下csv乱码问题

python2中:

  1. import csv,codecs
  2. f=open('temp.csv','w')
  3. f.write(codecs.BOM_UTF8)
  4. writer = csv.writer(f)
  5. writer.writerow(['奥迪','豆豆','方法'])
  6. f.close()

python3中:

  1. import csv,codecs
  2. f = codecs.open('temp.csv', 'w', 'utf_8_sig')
  3. writer = csv.writer(f)
  4. writer.writerow(['奥迪','爱迪生','方法'])
  5. f.close()
上一篇:Mongodb分片集群技术+用户验证


下一篇:django 导出excel react下载 --- 导出并下载