使用ajax在Django中将数据下载为Excel文件

Posted

技术标签:

【中文标题】使用ajax在Django中将数据下载为Excel文件【英文标题】:Download data as Excel file in Django with ajax 【发布时间】:2020-09-20 05:20:34 【问题描述】:

在带有 ajax 代码的页面上,我过滤了一个表单。 我正在使用 ajax 将过滤后的数据发送到 download_excel 方法,但下载不成功。 是什么原因?

view.py

def download_excel(request):
    jsdata = request.GET.get('listed_data')
    objdata = eval(jsdata)
    #objdata = ["id":"123123123","location":"test_location_1","device":"test_device_1","datetime":"12/12/2020","name":"asdas asdas","age":"21","gender":"male","temp":"37.6","mask":"0",risk":"1","id":"123123123","location":"test_location_1","device":"test_device_1","datetime":"12/12/2020","name":"asdas asdas","age":"21","gender":"male","temp":"37.6","mask":"0",risk":"1"...]

    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = "attachment; filename='Report.xls'"

    wb = xlwt.Workbook(encoding="utf-8")
    ws = wb.add_sheet("Report")

    row_num = 0

    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns = ["ID","Location","Device","Datetime","Full Name","Age Range","Gender","Body Temp","Mask","Risk"]

    for col_num in range(len(columns)):
        ws.write(row_num,col_num, columns[col_num], font_style)

    font_style = xlwt.XFStyle()

    for row in objdata:
        row_num += 1
        ws.write(row_num, 0, str(row["id"]), font_style)
        ws.write(row_num, 1, row["location"], font_style)
        ws.write(row_num, 2, row["device"], font_style)
        ws.write(row_num, 3, row["datetime"], font_style)
        ws.write(row_num, 4, row["name"], font_style)
        ws.write(row_num, 5, row["age"], font_style)
        ws.write(row_num, 6, row["gender"], font_style)
        ws.write(row_num, 7, row["temp"], font_style)
        ws.write(row_num, 8, row["mask"], font_style)
        ws.write(row_num, 9, row["risk"], font_style)


    wb.save(response)
    return response

urls.py

path('ajax/download_excel/', views.download_excel, name="download_excel")

模板html

function download_excel()
    $.ajax(
        url: "/events/ajax/download_excel/",
        data:
            'listed_data': "data|safe"
        
    )

【问题讨论】:

【参考方案1】:

这对我有用,例如

path('x1/', returnexcel, name='mreturnexcel'),

import xlsxwriter

def returnexcel(request):
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="mymodel.xlsx"'

    workbook = xlsxwriter.Workbook(response, 'in_memory': True)

# add a worksheet

    worksheet = workbook.add_worksheet()
    #########sql
    checkuserflagd2 = 0
    
    pky_idd2 = request.session['pk_id']
    print("download excel  pky_id")
    cursor3xd2 = connection.cursor()
    sql3xd2 = "select  id, userna, usercm, userpf, usermo, userd1 FROM myapp_document" # where id = " + str(pky_idd2)
    cursor3xd2.execute(sql3xd2 )#, docfile , mailfield, usercm, usermo, userna , userpf, userpw FROM myapp_document")
    transactions3xd2 = dictfetchall(cursor3xd2)
    
    ##############
    row_num = 0

    #font_style = xlwt.XFStyle()
    #font_style.font.bold = True

    columns = ["ID","userna","usercm","userpf","usermo","userd1"]

    for col_num in range(len(columns)):
        worksheet.write(row_num,col_num, columns[col_num])

    for row in transactions3xd2:
        row_num += 1
        worksheet.write(row_num, 0, str(row["id"]))
        worksheet.write(row_num, 1, str(row["userna"]))
        worksheet.write(row_num, 2, str(row["usercm"]))
        worksheet.write(row_num, 3, str(row["userpf"]))
        worksheet.write(row_num, 4, str(row["usermo"]))
        worksheet.write(row_num, 5, str(row["userd1"]))
        
    
        
        
    
    #worksheet.write_...
    worksheet.write('A1', 'Hello')

# use xlsxwriter routines to create the worksheet

# now write it out
    workbook.close()
    return response
////////////////

希望对你有帮助

【讨论】:

以上是关于使用ajax在Django中将数据下载为Excel文件的主要内容,如果未能解决你的问题,请参考以下文章

在 Django 中将 QuerySet 转换为 JSON

Django中将一个文本框中的数据通过点击按钮保存到数据库

django 中下载文件与下载保存为excel

带有ajax的django应用程序用于处理数据帧

使用 xlwt 将日期时间导出到 django 中的 excel

数据使用Excel导出下载