Django Pandas到http响应(下载文件)

Adr*_* Z. 16 python django pandas

Python:2.7.11

Django:1.9

熊猫:0.17.1

我该如何创建可能很大的xlsx文件下载?我正在从字典列表中创建一个带有pandas的xlsx文件,现在需要让用户可以下载它.该列表位于变量中,不允许在本地保存(在服务器上).

例:

df = pandas.DataFrame(self.csvdict)
writer = pandas.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
Run Code Online (Sandbox Code Playgroud)

这个例子只是创建文件并将其保存在执行脚本所在的位置.我需要的是将其创建为http响应,以便用户获得下载提示.

我发现了一些关于为xlsxwriter执行此操作的帖子,但是没有关于pandas的帖子.我也认为我应该使用'StreamingHttpResponse'而不是'HttpResponse'.

Pla*_*ush 11

我将详细说明@jmcnamara所写的内容.这适用于最新版本的Excel,Pandas和Django.import语句位于views.py的顶部,其余代码可能位于视图中:

import pandas as pd
from django.http import HttpResponse
try:
    from io import BytesIO as IO # for modern python
except ImportError:
    from io import StringIO as IO # for legacy python

# this is my output data a list of lists
output = some_function()
df_output = pd.DataFrame(output)

# my "Excel" file, which is an in-memory output file (buffer) 
# for the new workbook
excel_file = IO()

xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter')

df_output.to_excel(xlwriter, 'sheetname')

xlwriter.save()
xlwriter.close()

# important step, rewind the buffer or when it is read() you'll get nothing
# but an error message when you try to open your zero length file in Excel
excel_file.seek(0)

# set the mime type so that the browser knows what to do with the file
response = HttpResponse(excel_file.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

# set the file name in the Content-Disposition header
response['Content-Disposition'] = 'attachment; filename=myfile.xlsx'

return response
Run Code Online (Sandbox Code Playgroud)


Mar*_*inH 8

Jmcnamara指向你的方向.翻译成您的问题,您正在寻找以下代码:

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
Run Code Online (Sandbox Code Playgroud)

请注意,您要将数据保存到StringIO变量而不是文件位置.这样可以在生成响应之前阻止文件的保存.

  • 如何在Python 3中工作?我收到此错误消息:"字符串参数预期,得到'字节'" (2认同)
  • @Johan使用BytesIO代替StringIO。 (2认同)