python - 使用flask返回创建的excel文件

标签 python excel flask openpyxl pyexcel

我正在使用 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/

相关文章:

python - 如何将颜色调整到首选视觉范围?

python - 类型错误 : __init__() got an unexpected keyword argument 'family_or_realsock'

python - Tweepy Status.created_at时间与时间轴实际时间不一致

python - 使用 numpy.load 时遇到问题

python - python中函数之间的通信

javascript - Excel 和 IE7 - 防止 IE 打开 Excel 文件

c# - 将图像从内存流添加到 Excel 文档

excel - 不使用循环操作数组

python - Flask wtforms ValidationError 未向用户显示

python - 在 docker 中部署一个最小的 flask 应用程序 - 服务器连接问题