django pandas dataframe下载为excel文件

时间:2019-06-01 13:29:22

标签: django excel download

我有一个将放置在Docker容器中的Django应用。

应用程序以数据框格式准备数据。我想允许用户将数据作为excel文件下载到他/她的本地驱动器。

我过去曾经使用过df.to_excel,但这在这种情况下不起作用。

请告知最佳方法。

1 个答案:

答案 0 :(得分:1)

开始,您可以让Django直接写入BytesIO,例如:

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()
        return HttpResponse(b.getvalue(), content_type='application/vnd.ms-excel')

您可能需要安装Excel writer模块(例如xlsxwriteropenpyxl)。