Django-使用pd.read_html&df.to_excel创build一个可下载的excel文件

我目前有一个Python脚本,使用pd.read_html从一个网站拉数据。 然后我使用df.to_excel设置“xlsxwriter”作为引擎。

我试图find一种方法将其纳入Django的Web应用程序。 然而,我迷失在如何做到这一点,甚至知道如果可能的话。

我已经看到了一些在django中创build可下载的excel文件的方法,但没有一个将pandas作为在Excel文件中创build数据的驱动力。 我创build没有Django的Excel文件的Python代码有点长,所以不知道要显示什么。 以下是我的pandas代码的一部分:

xlWriter = pd.ExcelWriter(excel_sheet2, engine='xlsxwriter') workbook = xlWriter.book money_fmt = workbook.add_format({'num_format': 42, 'align': 'center', 'text_wrap': True}) text_fmt = workbook.add_format({'bold': True, 'align': 'center', 'text_wrap': True}) for i, df in enumerate(dfs): for col in df.columns[1:]: df.loc[df[col] == '-', col] = 0 df[col] = df[col].astype(float) df.to_excel(xlWriter, sheet_name='Sheet{}'.format(i)) 

以下是我的templates.html代码

 {% block content %} <form type="get" action="." style="margin: 0"> <input id="search_box" type="text" name="search_box" placeholder="Enter URL..." > <button id="search_submit" type="submit" >Submit</button> </form> {% endblock %} 

这是我的views.py的开始

 def financials(request): return render(request, 'personal/financials.html') if request.method == 'GET': search_query = request.GET.get('search_box', None) url = search_query dfs = pd.read_html(url, flavor='html5lib') 

你为什么不在Django视图中调用你的pandas函数,并将文件保存到/tmp 。 一旦你有了这个文件,你可以发送它,并告诉浏览器把它当作你的回应中的一个文件。

然后你可以返回文件

 from django.http import HttpResponse def my_view(request): # your pandas code here to grab the data response = HttpResponse(my_data, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="foo.xls"' return response 

https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

我只是想补充一下,我终于搞到了一切工作。 我没有在HttpResponse中包含数据,而是在wb.save()命令中包含响应。 这使得一切工作正常,包括我的电子表格格式下载之前。

 wb = load_workbook(excel_sheet2) response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename= "Data.xlsx"' wb.save(response) return response