natadecoco
natadecoco

Reputation: 83

Export data as csv is not working in django

I'm currently trying to export a csv file if the print button is clicked.

The problem is the file which generated is not .csv file

However, the file content is retrieve the values which I need (I checked by changing type of file manually. Hereby I attached the result). Could anyone show me the mistakes? Or is it related to any requirement plugin?

Any and all help is greatly appreciated!

enter image description here

import csv

query_data = search_data(request,request.user.userid)   


if (request.method == 'POST'):
        if 'csvexport' in request.POST:
            data = csv_export(query_data)
            return HttpResponse (data,content_type='text/csv')

--

def csv_export (data):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="file.csv"'
    writer = csv.writer(response)
    response.write('\ufeff'.encode('utf8'))
    writer.writerow([,'valData'
                     ,'value1'
                     ,'value2'])
    for rec in data:
        writer.writerow([rec['valData']
                         ,rec['value1']
                         ,rec['value2']])
    return response

--

def search_data(request,userid):
cursor = connection.cursor()

query = str("SELECT\n"
            " valData,\n"
            " MG0.valData as value1,\n"
            " MG1.valData as value2,\n"
        " FROM\n"
        " T_USER AS TU\n"

        " LEFT JOIN M_GENERAL AS MG0\n"
        " ON MG0.Cd='001'\n"

         " LEFT JOIN M_GENERAL AS MG1\n"
        " ON MG1.Cd='001'\n")

cursor.execute(query)
row = dictfetchall(cursor,)
return row

Upvotes: 0

Views: 594

Answers (1)

JPG
JPG

Reputation: 88499

Try this,

if (request.method == 'POST'):
        if 'csvexport' in request.POST:
            return csv_export(query_data)

Upvotes: 1

Related Questions