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()