导出数据为csv在django中不起作用

时间:2018-04-13 08:26:18

标签: django csv django-views

如果单击打印按钮,我目前正在尝试导出csv文件。

  

问题是生成的文件不是.csv文件

然而,文件内容是检索我需要的值(我通过手动更改文件类型来检查。因此我附上了结果)。 有人能告诉我错误吗?或者它与任何需求插件有关吗?

非常感谢任何和所有帮助!

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

1 个答案:

答案 0 :(得分:1)

试试这个,

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