简体   繁体   English

如何下载Excel文件

[英]How to download excel file

I am working with the GUI where there is a button. 我正在使用带有按钮的GUI。 On button click, an ajax call happens which returns a JSON to the backend in Django's view.py. 单击按钮时,会发生ajax调用,该调用将JSON返回到Django的view.py中的后端。 On the basis of the JSON, I am creating an excel file and the path of this file is returned to the place where ajax call happened. 基于JSON,我正在创建一个excel文件,并且此文件的路径返回到发生ajax调用的位置。 I want that file to download on the click of the same button. 我希望通过单击同一按钮下载该文件。

ie, is it possible to do all these operations (from ajax call to download the excel file) with one click of that button? 即,是否可以通过单击该按钮来执行所有这些操作(从ajax调用下载excel文件)?

edit

Path means the physical path of file system. 路径是指文件系统的物理路径。

Yes it is possible to do so. 是的,可以这样做。 Just make sure that the file is served from your STATIC_URL location ('static' folder by default). 只需确保从您的STATIC_URL位置(默认情况下为“静态”文件夹)提供文件即可。 In your views.py, 在您的views.py中,

def download(request):
    # /static/ is your STATIC_URL in settings
    file_path = "/static/xxxx.txt" # file path
    return JsonResponse({"file_path": file_path})

In your ajax code, 在您的Ajax代码中,

xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.status == 200) {
      window.location = this.file_path;
    }
};
xhttp.open("GET", "/download", true);
xhttp.send(); 

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

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