您现在的位置是:首页>文章详情

flask 导出数据至excel,创建响应生成下载文件实现方式

泛逸舟

#!/usr/bin/env python
#coding=utf-8
from flask import Flask, make_response, current_app, Response
import datetime
import xlwt
import StringIO
import mimetypes
from werkzeug.datastructures import Headers

def create_app():
    if not current_app:
        app = Flask(__name__)
    else:
        app = current_app
    return app


app = create_app()
# app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'


@app.route('/good/')
def index():
    filename = "".join(str(datetime.datetime.now()).split(" ")[0].split("-")) + "_" + "我的" + "审批报表.xlsx"
    wb = xlwt.Workbook()
    wb.encoding = 'gbk'
    ws = wb.add_sheet('1')
    ws.write(0, 1, '123')  # 如果要写中文请使用UNICODE
    output = StringIO.StringIO()
    # output.write(wb)
    wb.save(output)
    response = make_response(output.getvalue())
    response.headers['Content-Type'] = 'application/vnd.ms-excel'
    response.headers['Content-Disposition'] = 'attachment; filename=' + filename
    return response


@app.route('/export/')
def export_view():
    #########################
    # Code for creating Flask
    # response
    #########################
    response = Response()
    response.status_code = 200

    ##################################
    # Code for creating Excel data and
    # inserting into Flask response
    ##################################
    workbook = xlwt.Workbook()
    workbook.encoding = 'gbk'
    ws = workbook.add_sheet('1')
    ws.write(0, 1, '123')
    # .... code here for adding worksheets and cells

    output = StringIO.StringIO()
    workbook.save(output)
    response.data = output.getvalue()

    ################################
    # Code for setting correct
    # headers for jquery.fileDownload
    #################################
    filename = "陕西九曳" + "审批报表.xlsx"
    mimetype_tuple = mimetypes.guess_type(filename)

    # HTTP headers for forcing file download
    response_headers = Headers({
        'Pragma': "public",  # required,
        'Expires': '0',
        'Cache-Control': 'must-revalidate, post-check=0, pre-check=0',
        # 'Cache-Control': 'private',  # required for certain browsers,
        'Content-Type': mimetype_tuple[0],
        'Content-Disposition': 'attachment; filename=%s' % filename,
        'Content-Transfer-Encoding': 'binary',
        'Content-Length': len(response.data)
    })

    if not mimetype_tuple[1] is None:
        response.update({
            'Content-Encoding': mimetype_tuple[1]
        })

    response.headers = response_headers

    # as per jquery.fileDownload.js requirements
    # response.set_cookie('fileDownload', 'true', path='/')
    return response


if __name__ == '__main__':
    app.run(debug=True)

评论

评论插件