flask下載excel

flask 應用的基本結構:css

htmlweb.py
    -- static
    -- templates

bootstrap.min.css 放到 static 文件夾下,在 templates 文件夾下新建 index.html,裏面寫入以下信息:html

<html>
<head>
    <title>APIParse</title>
    <link rel="stylesheet" type="text/css" href="{{url_for('static', filename='css/bootstrap.min.css')}}"/>
</head>
<body>
TTYB
</body>
</html>

htmlweb.py 中寫入以下內容:web

from flask import Flask, render_template
from io import BytesIO
import xlsxwriter
def create_workbook():
    output = BytesIO()
    # 建立Excel文件,不保存,直接輸出
    workbook = xlsxwriter.Workbook(output, {'in_memory': True})
    # 設置Sheet的名字爲download
    worksheet = workbook.add_worksheet('download')
    # 列首
    title = ["col1","col2","col3"]
    worksheet.write_row('A1', title)
    dictList = [{"a":"a1","b":"b1","c":"c1"},{"a":"a2","b":"b2","c":"c2"},{"a":"a3","b":"b3","c":"c3"}]
    for i in range(len(dictList)):
        row = [dictList[i]["a"],dictList[i]["b"],dictList[i]["c"]]
        worksheet.write_row('A' + str(i + 2), row)
    workbook.close()
    response = make_response(output.getvalue())
    output.close()
    return response


app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return render_template("index.html")

from flask import make_response
@app.route('/download', methods=['GET'])
def download():

    response = create_workbook()
    response.headers['Content-Type'] = "utf-8"
    response.headers["Cache-Control"] = "no-cache"
    response.headers["Content-Disposition"] = "attachment; filename=download.xlsx"
    return response

if __name__ == "__main__":
    app.run(host='127.0.0.1', port=88, debug=True)

運行在瀏覽器訪問 127.0.0.1:88 能夠看到新建的頁面,在頁面訪問 127.0.0.1/download 能夠下載生成的 excel :flask

相關文章
相關標籤/搜索