当前位置:   article > 正文

flask 导出excel_flask导出excel

flask导出excel

Flask 导出Excel 的两种方法 ,第一种使用Flask-Excel

安装:

  1. pip install Flask-Excel
  2. pip install pyexcel-xls
  3. pip install pyexcel-xlsx
  4. pip install pyexcel-ods

除了安装主要的Falsk-Excel,还需要安装一些格式的扩展,需要导出什么格式就安装什么扩展

使用:

  1. #extendsions.py
  2. import flask_excel as excel
  3. #__init__.py
  4. from hifeiji.extendsions import excel
  5. excel.init_excel(app)
  6. #blueprint
  7. #activity.py
  8. import flask_excel as excel
  9. @activity_bp.route("/export", methods=['GET'])
  10. @login_required
  11. def export_records():
  12. content = [['No','Title','Name','Tel','Start','End','Service Time']]
  13. activityList = ActivityAtten.query.order_by(ActivityAtten.activity_start.asc()).all()
  14. if activityList:
  15. for value in activityList:
  16. new_content = []
  17. new_content = [value.activity_no,value.activity_title,value.activity_atten_name,value.activity_atten_tel,value.activity_start,value.activity_end,minutes2hours(value.activity_servicetime)]
  18. content.append(new_content)
  19. current_app.logger.info("exportActivity")
  20. return excel.make_response_from_array(content, "xlsx",
  21. file_name="exportActivity")

 首先,要初始化Flask-Excel,

excel.init_excel(app)

重点是最后一句

  1. return excel.make_response_from_array(content, "xlsx",file_name="exportActivity")
  2. #注释是这样的
  3. (function) make_response_from_array: (array, file_type, status=200, file_name=None, **keywords) -> None

第二种是使用 xlsxwriter

首先安装

pip install xlswriter

xlsxwriter 不需要初始化,可以直接调用,代码如下

  1. import xlsxwriter
  2. import io
  3. @activity_bp.route("/exportActivity",methods=['GET'])
  4. @login_required
  5. def exportActivity():
  6. output = io.BytesIO()
  7. workbook = xlsxwriter.Workbook(output)
  8. sheet = workbook.add_worksheet('考勤人员')
  9. activityList = Activity.query.order_by(Activity.starttime.asc()).all()
  10. format1 = {
  11. # 'bold': True, # 字体加粗
  12. 'align': 'center', # 水平位置设置:居中
  13. 'valign': 'vcenter', # 垂直位置设置,居中
  14. # 'font_size': 14, # '字体大小设置'
  15. 'border':1
  16. }
  17. title_format = workbook.add_format(format1)
  18. #构建格式并添加入实例
  19. format2={
  20. # 'bold':True,#字体加粗
  21. # 'num_format':'$#,##0',#货币数字显示样式
  22. 'align':'center',#水平位置设置:居中
  23. 'valign':'vcenter',#垂直位置设置,居中
  24. # 'font_size':16,#'字体大小设置'
  25. # 'font_name':'Courier New',#字体设置
  26. # 'italic':True,# 斜体设置
  27. # 'underline':1,#下划线设置 1.单下划线 2.双下划线 33.单一会计下划线 34双重会计下划线
  28. # 'font_color':"red",#字体颜色设置
  29. 'border':1,#边框设置样式1
  30. # 'border_color':'green',#边框颜色
  31. # 'bg_color':'#c7ffec',#背景颜色设置
  32. }
  33. content_format = workbook.add_format(format2)
  34. row = 0
  35. number = 1
  36. if activityList:
  37. for index in range(len(activityList)):
  38. activityAttenList = ActivityAtten.query.filter_by(activity_no=activityList[index].no).all()
  39. if activityAttenList:
  40. title_date = time.strftime("%Y-%m-%d", time.strptime(str(activityList[index].starttime), "%Y-%m-%d %H:%M:%S"))
  41. title = activityList[index].title
  42. # sheet.merge_range('B'+str(row)+':F'+str(row),str(index+1)+'.'+str(title_date)+' '+title)
  43. sheet.merge_range(row,1,row,5,str(number)+'.'+str(title_date)+' '+title,title_format)
  44. row = row+1
  45. sheet.set_column(row,1, 5)
  46. sheet.set_column(row,2, 10)
  47. sheet.set_column(row,3, 20)
  48. sheet.set_column(row,4, 20)
  49. sheet.set_column(row,5, 10)
  50. sheet.write(row,1,'序号',title_format)
  51. sheet.write(row,2,'姓名',title_format)
  52. sheet.write(row,3,'手机号码',title_format)
  53. sheet.write(row,4,'服务/培训时长',title_format)
  54. sheet.write(row,5,'备注',title_format)
  55. row = row+1
  56. for key in range(len(activityAttenList)):
  57. sheet.write(row,1,str(key+1),title_format)
  58. sheet.write(row,2,activityAttenList[key].activity_atten_name,title_format)
  59. sheet.write(row,3,activityAttenList[key].activity_atten_tel,title_format)
  60. sheet.write(row,4,minutes2hours(activityAttenList[key].activity_servicetime),title_format)
  61. sheet.write(row,5,'',title_format)
  62. row = row+1
  63. row = row+2 #每个活动换2
  64. number = number+1 #活动序号
  65. workbook.close()
  66. response = make_response(output.getvalue())
  67. response.headers['Content-Type'] = "application/x-xlsx"
  68. response.headers["Cache-Control"] = "no-cache"
  69. response.headers["Content-Disposition"] = "attachment; filename=download.xlsx"
  70. return response

有几个点需要注意,如果想设置单元格的样式,可以这样:

  1. format1 = {
  2. # 'bold': True, # 字体加粗
  3. 'align': 'center', # 水平位置设置:居中
  4. 'valign': 'vcenter', # 垂直位置设置,居中
  5. # 'font_size': 14, # '字体大小设置'
  6. 'border':1
  7. }
  8. title_format = workbook.add_format(format1)
  9. #.......
  10. sheet.write(row,1,'序号',title_format)

write() 的方法是这样的

  1. #跟踪 write()方法,是这样的
  2. def write(self, row, col, *args):
  3. """
  4. Write data to a worksheet cell by calling the appropriate write_*()
  5. method based on the type of data being passed.
  6. Args:
  7. row: The cell row (zero indexed).
  8. col: The cell column (zero indexed).
  9. *args: Args to pass to sub functions.
  10. Returns:
  11. 0: Success.
  12. -1: Row or column is out of worksheet bounds.
  13. other: Return value of called method.
  14. """
  15. return self._write(row, col, *args)

行和列都从0 开始,比如A1,其实就是0,0

make_response() 方法使用时,要注意,是使用flask 中的make_response()方法,而不是pyexcel 中的 make_response(),当初我就是在这里卡住了!两个方法是不一样的。

跟住make_response()方法

  1. def make_response(*args: t.Any) -> "Response":
  2. """Sometimes it is necessary to set additional headers in a view. Because
  3. views do not have to return response objects but can return a value that
  4. is converted into a response object by Flask itself, it becomes tricky to
  5. add headers to it. This function can be called instead of using a return
  6. and you will get a response object which you can use to attach headers.
  7. If view looked like this and you want to add a new header::
  8. def index():
  9. return render_template('index.html', foo=42)
  10. You can now do something like this::
  11. def index():
  12. response = make_response(render_template('index.html', foo=42))
  13. response.headers['X-Parachutes'] = 'parachutes are cool'
  14. return response
  15. This function accepts the very same arguments you can return from a
  16. view function. This for example creates a response with a 404 error
  17. code::
  18. response = make_response(render_template('not_found.html'), 404)
  19. The other use case of this function is to force the return value of a
  20. view function into a response which is helpful with view
  21. decorators::
  22. response = make_response(view_function())
  23. response.headers['X-Parachutes'] = 'parachutes are cool'
  24. Internally this function does the following things:
  25. - if no arguments are passed, it creates a new response argument
  26. - if one argument is passed, :meth:`flask.Flask.make_response`
  27. is invoked with it.
  28. - if more than one argument is passed, the arguments are passed
  29. to the :meth:`flask.Flask.make_response` function as tuple.
  30. .. versionadded:: 0.6
  31. """
  32. if not args:
  33. return current_app.response_class()
  34. if len(args) == 1:
  35. args = args[0]
  36. return current_app.make_response(args)

从注释可以知道,response = make_response(render_template('index.html', foo=42))可以使用html 转存生成其他文件

以上是两种导出excel 的方法,

如果只是单纯导出报表,无需其他样式的,可以使用flask-excel,因为比较简单方便。

如果是需要有一定样式的,比如合拼单元格之类的,xlsxwriter 好用

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/464544
推荐阅读
相关标签
  

闽ICP备14008679号