我正在使用 openpyxl 创建一个 excel 文件,我想将其作为文件下载返回(因此不保存在本地)。
我可以很好地创建 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 来创建一个精美的 Excel 工作表。显然,如果 pyexcel 和 openpyxl 能够通信那就没问题了。
有什么想法吗?
干杯,迈克
最佳答案
由于我在重新组装零散且有点过时的代码片段时遇到了歧义,因此我想在这里留下另一个答案。这在技术上是相同的,但是是一个相当完整的代码片段,并且是最新的。
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'
}
)
关于python - 使用flask返回创建的excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42957871/