Create Excel file with xlwt and insert in Flask response valid for jquery.fileDownload


/ Published in: Python
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. import xlwt
  2. import StringIO
  3. import mimetypes
  4. from flask import Response
  5. from werkzeug.datastructures import Headers
  6.  
  7. #... code for setting up Flask
  8.  
  9. @app.route('/export/')
  10. def export_view():
  11. #########################
  12. # Code for creating Flask
  13. # response
  14. #########################
  15. response = Response()
  16. response.status_code = 200
  17.  
  18.  
  19. ##################################
  20. # Code for creating Excel data and
  21. # inserting into Flask response
  22. ##################################
  23. workbook = xlwt.Workbook()
  24.  
  25. #.... code here for adding worksheets and cells
  26.  
  27. output = StringIO.StringIO()
  28. workbook.save(output)
  29. response.data = output.getvalue()
  30.  
  31. ################################
  32. # Code for setting correct
  33. # headers for jquery.fileDownload
  34. #################################
  35. filename = export.xls
  36. mimetype_tuple = mimetypes.guess_type(filename)
  37.  
  38. #HTTP headers for forcing file download
  39. response_headers = Headers({
  40. 'Pragma': "public", # required,
  41. 'Expires': '0',
  42. 'Cache-Control': 'must-revalidate, post-check=0, pre-check=0',
  43. 'Cache-Control': 'private', # required for certain browsers,
  44. 'Content-Type': mimetype_tuple[0],
  45. 'Content-Disposition': 'attachment; filename=\"%s\";' % filename,
  46. 'Content-Transfer-Encoding': 'binary',
  47. 'Content-Length': len(response.data)
  48. })
  49.  
  50. if not mimetype_tuple[1] is None:
  51. response.update({
  52. 'Content-Encoding': mimetype_tuple[1]
  53. })
  54.  
  55. response.headers = response_headers
  56.  
  57. #as per jquery.fileDownload.js requirements
  58. response.set_cookie('fileDownload', 'true', path='/')
  59.  
  60. ################################
  61. # Return the response
  62. #################################
  63. return response

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.