使用flask response 和xlwt创建excel下载文件

import xlwt
import StringIO
import mimetypes
from flask import Response
from werkzeug.datastructures import Headers
 
#... code for setting up Flask
 
@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()
 
    #.... 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 = export.xls
    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 the response
    #################################
    return response

猜你喜欢

转载自my.oschina.net/u/2345713/blog/1625499