Django HttpResponse:用户单击按钮后下载Excel

时间:2018-10-20 16:50:39

标签: django python-3.x

在我的Django项目中,我需要将内存中的Excel文件发送到客户端进行下载。用户单击按钮后,应该开始下载。

到目前为止,我已经在app/views.py中使用了这段代码:

import pandas as pd
from io import BytesIO as IO
from django.http import HttpResponse
import xlsxwriter


def write_to_excel():

    df_output = pd.DataFrame({'col1': ['abc', 'def'], 'col2': ['ghi', 'jkl']})

    # my "Excel" file, which is an in-memory output file (buffer) 
    # for the new workbook
    excel_file = IO()

    xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter')

    df_output.to_excel(xlwriter, 'sheetname')

    xlwriter.save()
    xlwriter.close()

    # rewind the buffer
    excel_file.seek(0)

    # set the mime type so that the browser knows what to do with the file
    response = HttpResponse(excel_file.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    # set the file name in the Content-Disposition header
    response['Content-Disposition'] = 'attachment; filename=myfile.xlsx'

    return response

这是我的HTML文件:

<!DOCTYPE html>
<html>
<head>    
    <title>Generate Data</title>    
</head>
<body>
    <form method="post">
        <!-- {% csrf_token %}
        {{ form.as_p }} -->
        <input type="submit" value="Excel">
    </form>

</html>
</body>

上面的代码正在运行,并在我运行应用程序后立即下载具有正确数据的Excel文件。我希望它一直等到用户单击Excel按钮,然后下载电子表格。我怎样才能做到这一点?我是Django和HTML的新手。

1 个答案:

答案 0 :(得分:0)

在没有看到urls.py文件的情况下,很难准确地将您定向,但是看起来应该像这样:

Views.py

def exportFile():

    df = pd.DataFrame({'col1': ['abc', 'def'], 'col2': ['ghi', 'jkl']})

    resp = HttpResponse(content_type='text/csv')
    resp['Content-Disposition'] = 'attachment; filename=myFile.csv'

    df.to_csv(path_or_buf=resp, sep=',', index=False)
    return resp

myApp \ urls.py

urlpatterns = [
               path('myApp/export/', include('app.urls')),
              ]

app \ urls.py

urlpatters = [
              path('myApp/export/', views.exportFile, name='exportFile'),
             ]

myApp.html

<form name="exportFile" action="/myApp/export/" method="get">
<input type="submit" id="exportFile" name="exportFile" value="Export">
</form>