使用xlwt创建Excel文件并插入对有效的响应jquery.fileDownload文件下载
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用xlwt创建Excel文件并插入对有效的响应jquery.fileDownload文件下载相关的知识,希望对你有一定的参考价值。
A combinations of 3 technologies.Needed to create Excel files within a Python Flask web framework environment and have it sent via HTTP to client to be handled by the jquery.fileDownload library.
Notes:
1. Flask has to set a cookie specified by jquery.fileDownload
2. Divided code into blocks of code that can be maybe reusable in functions
3. 'app' is not declared but it is obvious a Flask application object
relevant projects:
1. http://flask.pocoo.org/
2. pypi.python.org/pypi/xlwt and www.python-excel.org/
3. https://github.com/johnculviner/jquery.fileDownload
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
以上是关于使用xlwt创建Excel文件并插入对有效的响应jquery.fileDownload文件下载的主要内容,如果未能解决你的问题,请参考以下文章