【问题标题】:Return Excel file from django view to html for downloading at client将 Excel 文件从 django 视图返回到 html 以便在客户端下载
【发布时间】:2020-02-26 07:28:28
【问题描述】:

我有一个 django 应用程序,其中在服务器端生成 excel 文件,我希望在客户端下载它。 我正在通过 JavaScript 中的 Ajax 调用发送请求,该请求会发送到服务器生成需要下载的 excel。 视图应该生成 http 响应,将 excel 文件发送到 html,可以在客户端下载到文件

【问题讨论】:

    标签: django python-3.x


    【解决方案1】:

    这并不像您想象的那么复杂。事实上,据我了解,您有一个 Django 模型,您需要将一些实例的数据导出到一个 .xlsx 文件中。

    我建议以下简单的解决方案:

    import openpyxl
    from openpyxl.utils import get_column_letter
    from django.http.response import HttpResponse
    
    def method(request, **kwargs):
        queryset = ModelName.objects.filter()   # adjust accordingly
    
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename=this-is-your-filename.xlsx'
        wb = openpyxl.Workbook()
        ws = wb.get_active_sheet()
        ws.title = "Your Title"
    
        row_num = 0
    
        columns = [
            ("ID", 5),
            (u'Name', 20),
        ]
    
        for col_num in range(len(columns)):
            c = ws.cell(row=row_num + 1, column=col_num + 1)
            c.value = columns[col_num][0]
            ws.column_dimensions[get_column_letter(col_num + 1)].width = columns[col_num][1]
    
        for obj in queryset:
            row_num += 1
            row = [
                obj.pk,
                obj.name,
            ]
            for col_num in range(len(row)):
                c = ws.cell(row=row_num + 1, column=col_num + 1)
                c.value = row[col_num]
    
        wb.save(response)
        return response
    

    请记住,您需要先使用pip install openpyxl 安装openpyxl 库。

    【讨论】:

    • 其实我是用xlsxwriter生成excel文件并保存在服务器上的。我可以将此保存的 .xlsx 文件作为 http 响应发送吗?
    • 我想不出你不能这样做的原因。您必须在响应中设置Content-Disposition HTTP 标头,以及正确的content_type
    • 好的,谢谢....我会尝试一次..我是否也需要在 html 中添加任何内容,否则返回响应会自动下载文件
    • 它应该会自动提示用户下载文件
    • 我在网站上收到了回复,但没有出现下载提示
    【解决方案2】:

    我必须完成这个确切的任务并最终使用以下方法。而不是使用 AJAX 调用,我只是这样做

    window.location.pathname = "/relative/path/to/url/"
    

    在按钮的 Javascript 点击处理程序中。

    在 Django 中,我使用以下代码(我使用的是 XlsxWriter,但您可以使用任何您希望创建的 XLSX 文件):

        excel_file = BytesIO()
        workbook = xlsxwriter.Workbook(excel_file)
    
        # Code to populate the workbook
    
        # Here comes the magic
        workbook.close()
        excel_file.seek(0)
        response = HttpResponse(excel_file.read(),
                                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename=somename.xlsx'
        return response
    

    以这种方式调用时,会下载创建的 Excel 文件,并且用户仍停留在调用页面上,这正是我想要的行为。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2013-11-02
      • 2016-02-12
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      相关资源
      最近更新 更多