无法打开django生成的excel文件。

问题描述 投票:0回答:1

比如说有一个像pandas的数据框架。

                          mediabuy      cpa        mediabuy        cpc          
cost        2020-02         0.00       371929.95   15956581.16    16328511.11
            2020-04        1311.92     224747.07   26710431.81    26936490.80
total                      1311.92     596677.02   42667012.97     43265001.91

我想在django中创建一个excel文件,我已经尝试了如下代码。


# return excel view


            df = pd.DataFrame(data, index=index, columns=column)

            # saved as excel
            excel_writer = pd.ExcelWriter(path='temp.xlsx', engine='openpyxl')
            df.to_excel(excel_writer)
            wb = excel_writer.book

            response = HttpResponse(save_virtual_workbook(wb))
            response["Content-Type"] = 'application/vnd.ms-excel'
            response['Content-Disposition'] = 'attachment; filename={}.xlsx'.format("data"))
            return response

我的工作是 python3.6.8, django2.2.4, pandas1.0.3, openpyxl3.0.3

但我总是收到一个错误信息,说 "excel文件无法打开,因为文件格式或文件扩展名无效"。

我为什么会出现这个错误?

谢谢。

python django excel pandas
1个回答
1
投票

除非数据框架中的数据结构有问题,否则你应该可以使用以下方法来实现。

from io import BytesIO

df = pd.DataFrame(data, index=index, columns=column)

stream_file = BytesIO()
df.to_excel(stream_file)
stream_file.seek(0)

response = HttpResponse(stream_file)
response["Content-Type"] = 'application/vnd.ms-excel'
response['Content-Disposition'] = 'attachment; filename={}.xlsx'.format("data")
return response
© www.soinside.com 2019 - 2024. All rights reserved.