使用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
  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

以上是关于使用xlwt创建Excel文件并插入对有效的响应jquery.fileDownload文件下载的主要内容,如果未能解决你的问题,请参考以下文章

新建excel文件——xlwt库——新建一个最简单的excel表格——并写入数据

python如何对excel数据进行处理

django excel xlwt

使用Python xlwt写excel文件

Python模块xlwt对excel进行写入操作

python xlwt,xlutils 在excel里面如何插入一行数据