jsc*_*tor 5 django excel download
我有一个将放置在 Docker 容器中的 Django 应用程序。
该应用程序以 Dataframe 格式准备数据。我想允许用户将数据作为 excel 文件下载到他/她的本地驱动器。
我过去曾使用过 df.to_excel,但这在这种情况下不起作用。
请建议最好的方法来做到这一点。
从pandas-0.17 开始,您可以让 DjangoBytesIO直接写入 a ,例如:
from django.http import HttpResponse
from io import BytesIO
def some_view(request):
with BytesIO() as b:
# Use the StringIO object as the filehandle.
writer = pd.ExcelWriter(b, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
# Set up the Http response.
filename = 'django_simple.xlsx'
response = HttpResponse(
b.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return responseRun Code Online (Sandbox Code Playgroud)
您可能需要安装 Excel 编写器模块(如xlsxwriter、 或openpyxl)。