簡體   English   中英

使用燒瓶返回創建的 excel 文件

[英]return a created excel file with flask

我正在使用 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 進行通信就可以了。

有什么想法嗎?

干杯,邁克

根據查理克拉克的提示,我最終確定了以下解決方案。

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)

由於我在重新組裝零散的和有點老式的代碼片段時模棱兩可,我想在這里留下另一個答案。 這在技術上是相同的,但是一個非常完整的代碼片段,它有點更新。

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


當我遇到同樣的問題時,我所做的是我在服務器上編寫了一個臨時文件,我讓我的create_excel_sheet(data)函數返回文件名,然后使用flask 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM