Django导出excel中文乱码解决方案
Posted 413Xiaol
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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中:
- import csv,codecs
- f=open(‘temp.csv‘,‘w‘)
- f.write(codecs.BOM_UTF8)
- writer = csv.writer(f)
- writer.writerow([‘奥迪‘,‘豆豆‘,‘方法‘])
- f.close()
python3中:
- import csv,codecs
- f = codecs.open(‘temp.csv‘, ‘w‘, ‘utf_8_sig‘)
- writer = csv.writer(f)
- writer.writerow([‘奥迪‘,‘爱迪生‘,‘方法‘])
- f.close()
以上是关于Django导出excel中文乱码解决方案的主要内容,如果未能解决你的问题,请参考以下文章