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