return 一个用 flask 创建的 excel 文件

return a created excel file with flask

我正在使用 openpyxl 创建一个 excel 文件,我想 return 作为文件下载(因此不保存在本地)。

我可以很好地创建 excel 文件并将其保存到磁盘。但是,我无法下载此文件。

尝试 1:

import flask_excel as excel

...

create_excel_sheet(data) # internally save the sheet with name sheet.xlsx

output = excel.make_response()
output.headers["Content-Disposition"] = "attachment; filename=" + \
                                        'sheet.xlsx'
output.headers["Content-type"] = "application/vnd.openxmlformats-\
officedocument.spreadsheetml.sheet"

return output

这 return 是一个名为 sheet.xlsx

的空文本文件

尝试 2: wb = create_excel_sheet(数据) # return openpyxl 工作簿

output = excel.make_response(wb)
output.headers["Content-Disposition"] = "attachment; filename=" + \
                                        'sheet.xlsx'
output.headers["Content-type"] = "application/vnd.openxmlformats-\
officedocument.spreadsheetml.sheet"

return output

我不想对数据使用 pyexcel,因为我需要 openpyxl 来创建一个奇特的 excel sheet。显然,如果 pyexcel 和 openpyxl 进行了通信,那就没问题了。

有什么想法吗?

干杯,迈克

当我遇到同样的问题时,我所做的是在服务器上写了一个临时文件,我将 create_excel_sheet(data) 函数设置为 return 文件名,然后用烧瓶 send_file() 函数:

send_file( create_excel_sheet_and_return_filename(data) )

您可以使用 python 创建临时文件的模块,当进程存在时这些文件会被删除,如果安全是个问题则使用授权。

所有 看起来 都是正确的。您实际上是从您的视图中返回响应吗?我认为问题中的这一点并不清楚,但可以解释问题。

例如:

@app.route('/download_sheet')
def download():
    create_excel_sheet(data)
    output = excel.make_response()
    output.headers["Content-Disposition"] = "attachment; filename=sheet.xlsx"
    output.headers["Content-type"] = "application/vnd.openxmlformats-\
officedocument.spreadsheetml.sheet"
    return output  # Send the response to the user

...

<a href="{{ url_for('app.download') }}">Click here for Sheet</a>

根据 Charlie Clark 的提示,我最终确定了以下解决方案。

output = make_response(create_sheet(data))
output.headers["Content-Disposition"] = "attachment; filename=" + \
                                        "sheet.xlsx"
output.headers["Content-type"] = \
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

其中

def create_sheet(data):

returns

return save_virtual_workbook(wb)

由于我在重新组合支离破碎的代码片段和一些 old-fashioned 代码片段时遇到了歧义,因此我想在这里留下另一个答案。这在技术上是相同的,但是是一个非常完整的代码片段,它更新了一点。

from flask import Response
from openpyxl import Workbook
from openpyxl.writer.excel import save_virtual_workbook

...

@app.route("/download")
def download():
    wb = Workbook()
    
    ...

    return Response(
        save_virtual_workbook(wb),
        headers={
            'Content-Disposition': 'attachment; filename=sheet.xlsx',
            'Content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }
    )