[Answer]-Write csv from dictionary

1👍

Use csv:

import csv

def your_view(request, ...):
    csv_data = {
        'data': [
            ('quick', 'brown', 'fox', 'jump'),
            ('over', 'the', 'lazy', 'dog')
        ],
        'total': 23,
        'subtotal': 4
    }

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="some_file.csv"'
    writer = csv.writer(response, delimiter='\t')
    writer.writerow(['header1', 'header2', 'header3', 'header4'])
    writer.writerows(csv_data['data'])
    writer.writerow(['tota', 'subtotal'])
    writer.writerow([csv_data['total'], csv_data['subtotal']])
    return response

Leave a comment