(django1.11, python3.7.x)
open()
使わずに HttpResponse
でやる場合のやつ
import csv import io 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"' sio = io.StringIO() writer = csv.writer(sio) writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) response.write(sio.getvalue().encode('utf_8_sig')) return response