简体   繁体   English

如何使用 Django 下载 xlsx 文件?

[英]How do I download xlsx file with Django?

I tried to make a button for downloading a .xlsx file using Django so I followed this tutorial: https://xlsxwriter.readthedocs.io/example_django_simple.html我试图制作一个使用 Django 下载.xlsx文件的按钮,所以我遵循了本教程: https : //xlsxwriter.readthedocs.io/example_django_simple.html

Now I have an HTTP response, but no download prompt is showing.现在我有一个 HTTP 响应,但没有显示下载提示。

Here are some parts of my code :这是我的代码的一些部分:

views.py:视图.py:

def xlsx(request):
    if request.method == "POST":
        output = io.BytesIO()
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet("hello")
        worksheet.write(0,0, 'Client')
        workbook.close()
        output.seek(0)

    filename = 'EdedocBilling.xlsx'
    response =  HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
    return response

index.html索引.html

<form>...</form>
<button type = "button" id = "saveID"
    onclick = "$.ajax({
        type: 'POST',
        url: 'xlsx',
        async: false,
        data: $('form').serialize(),
        success : console.log(' Success')
    })">
    Generate
</button>

I removed the code where I process the data because the generated .xlsx works fine.我删除了处理数据的代码,因为生成的.xlsx工作正常。 (I tested creating the file on the server and it worked.) (我测试了在服务器上创建文件并成功。)

Here are the HTTP response headers:以下是 HTTP 响应标头:

HTTP/1.1 200 OK
Date: Thu, 08 Jul 2021 14:47:37 GMT
Server: WSGIServer/0.2 CPython/3.8.8
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Content-Disposition: attachment; filename="EdedocBilling.xlsx"
X-Frame-Options: DENY
Content-Length: 5252
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin

Does somebody have a solution?有人有解决方案吗? Thanks!谢谢!

This is due to the nature of AJAX, and how browsers handle all of this.这是由于 AJAX 的性质以及浏览器如何处理所有这些。

Have a look at the different answers to question Is it possible to download a file with HTTP POST?查看问题的不同答案是否可以使用 HTTP POST 下载文件? . .

Using MEDIA and a URL Pattern使用媒体和 URL 模式

Return a URL in the response of the POST request and implement a URL pattern that delivers the file content.在 POST 请求的响应中返回一个 URL,并实现一个传递文件内容的 URL 模式。

This is of course a bit more effort but it would be a good solution if you website has to scale.这当然需要更多的努力,但如果您的网站必须扩展,这将是一个很好的解决方案。

Steps:脚步:

  1. create a Django model for the Excel sheet and store the generated files in the MEDIA folder: see https://docs.djangoproject.com/en/3.2/topics/files/ on details how to do this.为 Excel 工作表创建一个 Django 模型并将生成的文件存储在 MEDIA 文件夹中:有关如何执行此操作的详细信息,请参阅https://docs.djangoproject.com/en/3.2/topics/files/ The model should at least have a slug and a file field, and maybe a date field for handling expiry if you want the access to be only temporary available.该模型至少应该有一个 slug 和一个文件字段,如果您希望访问权限仅是临时可用的,则可能还有一个用于处理到期的日期字段。
  2. in your urls.py create a route that identifies a specific excel, eg /generated/slug:slug.xls.在您的 urls.py 中创建一个标识特定 excel 的路由,例如 /generated/slug:slug.xls。 Implement get_absolute_url() on your model returning this route.在返回此路由的模型上实现get_absolute_url()
  3. from your post request do not return the generated file but return the result of obj.get_absolute_url as text content to be handled in JS.从你的 post 请求不返回生成的文件,而是返回 obj.get_absolute_url 的结果作为要在 JS 中处理的文本内容。
  4. in your AJAX success handler, redirect the browser to this URL.在您的 AJAX 成功处理程序中,将浏览器重定向到此 URL。
  5. in the view of this route, return the file.在此路由的视图中,返回文件。 You can also check for authorization and expiry here.您还可以在此处检查授权和到期时间。

In a production setup, you can also configure your Reverse Proxy (eg nginx) to deliver the files, and your Django view only sets a header (X-Accel-Redirect) that indicates to the proxy which file to deliver.在生产设置中,您还可以配置您的反向代理(例如 nginx)来交付文件,并且您的 Django 视图仅设置一个标头(X-Accel-Redirect),指示代理要交付哪个文件。 See https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/ for more on this.有关更多信息,请参阅https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM