2

我正在使用 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) # return openpyxl workbook

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 进行通信就可以了。

有什么想法吗?

干杯,迈克

4

4 回答 4

3

根据查理克拉克的提示,我最终确定了以下解决方案。

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)
于 2017-03-24T10:36:38.793 回答
3

由于我在重新组装零散的和有点老式的代码片段时模棱两可,我想在这里留下另一个答案。这在技术上是相同的,但是一个非常完整的代码片段,它有点更新。

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'
        }
    )


于 2020-08-04T06:24:39.317 回答
1

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

send_file( create_excel_sheet_and_return_filename(data) )

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

于 2017-03-22T17:47:21.800 回答
0

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

例如:

@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>
于 2017-03-22T21:15:33.893 回答