用烧瓶返回一个创build好的excel文件

我正在使用openpyxl创build一个excel文件,我希望将其作为文件下载返回(因此不在本地保存)。

我可以创build好的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 

这将返回一个名为sheet.xlsx的空文本文件

尝试2:wb = create_excel_sheet(data)#返回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来创build一个奇特的excel表单。 很明显,如果pyexcel和openpyxl传达的话就没问题了。

有什么想法吗?

干杯,迈克

当我遇到同样的问题时,我所做的是我在服务器上写了一个临时文件,我使用create_excel_sheet(data)函数返回了文件名,然后使用flask send_file()函数返回文件:

 send_file( create_excel_sheet_and_return_filename(data) ) 

您可以使用创build临时文件的python模块,当进程存在时删除临时文件,并在安全性问题时使用授权。

基于查理·克拉克的暗示,我终于解决了以下的问题。

 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): 

回报

 return save_virtual_workbook(wb) 

这一切看起来正确。 你实际上是从你的观点回应的回应? 这个问题并不清楚,我想可以解释这个问题。

例如:

 @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>