前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >flask下载excel

flask下载excel

作者头像
机器学习和大数据挖掘
发布2019-07-01 18:28:07
1.5K0
发布2019-07-01 18:28:07
举报
文章被收录于专栏:数据挖掘

flask 应用的基本结构:

代码语言:javascript
复制
htmlweb.py
    -- static
    -- templates

bootstrap.min.css 放到 static 文件夹下,在 templates 文件夹下新建 index.html,里面写入如下信息:

代码语言:javascript
复制
<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 中写入如下内容:

代码语言:javascript
复制
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 :

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-03-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档