Django Pandas对http的响应(下载文件) [英] Django Pandas to http response (download file)
问题描述
Python:2.7.11
Python: 2.7.11
Django:1.9
Django: 1.9
熊猫:0.17.1
我应该如何创建潜在的大型xlsx文件下载?我正在用词典列表中的熊猫创建一个xlsx文件,现在需要给用户下载的可能性。该列表位于变量中,并且不允许在本地保存(在服务器上)。
How should I go about creating a potentially large xlsx file download? I'm creating a xlsx file with pandas from a list of dictionaries and now need to give the user possibility to download it. The list is in a variable and is not allowed to be saved locally (on server).
示例:
df = pandas.DataFrame(self.csvdict)
writer = pandas.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
此示例仅创建文件并将其保存在执行脚本所在的位置。我需要将其创建为http响应,以便用户获得下载提示。
This example would just create the file and save it where the executing script is located. What I need is to create it to a http response so that the user would get a download prompt.
我发现了一些有关为xlsxwriter进行此操作的帖子,但没有大熊猫。我还认为我应该为此使用'StreamingHttpResponse'而不是'HttpResponse'。
I have found a few posts about doing this for a xlsxwriter but non for pandas. I also think that I should be using 'StreamingHttpResponse' for this and not a 'HttpResponse'.
推荐答案
Jmcnamara指向您严格的方向。转换为您的问题,您正在寻找以下代码:
Jmcnamara is pointing you in the rigth direction. Translated to your question you are looking for the following code:
sio = StringIO()
PandasDataFrame = pandas.DataFrame(self.csvdict)
PandasWriter = pandas.ExcelWriter(sio, engine='xlsxwriter')
PandasDataFrame.to_excel(PandasWriter, sheet_name=sheetname)
PandasWriter.save()
sio.seek(0)
workbook = sio.getvalue()
response = StreamingHttpResponse(workbook, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
请注意,您正在将数据保存到StringIO变量,并且而不是文件位置。这样可以防止在生成响应之前保存文件。
Notice the fact that you are saving the data to the StringIO variable and not to a file location. This way you prevent the file being saved before you generate the response.
这篇关于Django Pandas对http的响应(下载文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!