簡體   English   中英

在Flask中返回Excel文件

[英]Return Excel file in Flask

我正在用python 3構建Flask應用程序。我正在嘗試寫入輸出並響應下載。 我要做的就是將sqlite3 db內容寫入一個Excel文件,嘗試發送到客戶端進行下載。 在創建excel文件之前,一切似乎工作正常。 我無法發送給客戶。

@app.route('/download', methods=['GET'])
def export_db():
    values = execute("SELECT * from table",[])
    wb = Workbook()
    ws = wb.active

    for item in values.fetchall():
        ws.append(item)
    wb.save('example.xlsx')

    output = make_response(wb)
    output.headers["Content-Disposition"] = "attachment; filename=" + 
    "example.xlsx"
    output.headers["Content-type"] = "application/vnd.openxmlformats-
    officedocument.spreadsheetml.sheet"
    return output

我收到的錯誤消息是,

Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1612, 
in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1598, 
in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/user/Documents/main.py", 
line 218, in export_db
output = make_response(wb)
File "/usr/local/lib/python3.5/dist-packages/flask/helpers.py", line 
191, in make_response
return current_app.make_response(args)
File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1740, 
in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/usr/local/lib/python3.5/dist-packages/werkzeug/wrappers.py", 
line 911, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/usr/local/lib/python3.5/dist-packages/werkzeug/wrappers.py", 
line 59, in _run_wsgi_app
return _run_wsgi_app(*args)
File "/usr/local/lib/python3.5/dist-packages/werkzeug/test.py", line 
884, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'Workbook' object is not callable

我已經提到了幾個類似的問題,但是似乎沒有一個有用的問題。 任何幫助將不勝感激。

注意:當我嘗試將文件路徑添加到make_response時,它將文件路徑作為字符串並返回給我一個.xlsx文件,其中文件路徑為內容。 知道我在做什么錯嗎?

這樣的事情應該起作用:

from flask import send_file
from xlsxwriter import Workbook

@app.route('/download', methods=['GET'])
def export_db():
    values = execute("SELECT * from table",[])
    wb = Workbook('path/to/workbook.xlsx')
    wb.add_worksheet('All Data')

    for item in values.fetchall():
        wb.write(item)
    wb.close()

    return send_file('path/to/workbook.xlsx')

暫無
暫無

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

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