当前位置:   article > 正文

Flask+vue+axios完成导出Excel表格的功能_flask 导出excel

flask 导出excel
 前段部分:
1.分装api:在 src/api/volunteer.js文件内
注意:一定要加上" responseType: 'blob' "否则打开文件后是乱码或者根本打不开文件
  1. import request from "@/utils/request";
  2. //导出
  3. export function importVolunteer(data) {
  4. return request({
  5. method: 'post',
  6. url: '/volunteer/download_excel',
  7. data,
  8. responseType: 'blob'
  9. })
  10. }
2. 调用接口 :在src/views/volunteer.vue文件内
  1. // 导出按钮点击事件处理
  2. async importHandle() {
  3. try {
  4. // 调用导出的接口
  5. const res = await importVolunteer();
  6. // 处理导出的Excel文件
  7. const blob = new Blob([res], {type:'application/vnd.ms-excel;charset=utf-8'});
  8. const url = window.URL.createObjectURL(blob);
  9. const link = document.createElement('a');
  10. link.href = url;
  11. link.setAttribute('download', '志愿者导出表');
  12. document.body.appendChild(link);
  13. link.click();
  14. document.body.removeChild(link);
  15. window.URL.revokeObjectURL(url);
  16. } catch (error) {
  17. console.error(error);
  18. }
  19. }
后端部分:
第一种:不存储在后端直接返回给前端
  1. import io
  2. import xlwt as xlwt
  3. from flask import make_response
  4. from flask_backend.models import Volunteer
  5. @volunteer_blue.route('/download_excel', methods=['POST'])
  6. def exportData():
  7. wb = xlwt.Workbook()
  8. ws = wb.add_sheet('志愿者报表')
  9. first_col = ws.col(0) # xlwt中是行和列都是从0开始计算的
  10. second_col = ws.col(1)
  11. third_col = ws.col(2)
  12. four_col = ws.col(3)
  13. five_col = ws.col(4)
  14. six_col = ws.col(5)
  15. seven_col = ws.col(6)
  16. first_col.width = 128 * 20
  17. second_col.width = 230 * 20
  18. third_col.width = 230 * 20
  19. four_col.width = 128 * 20
  20. five_col.width = 230 * 20
  21. six_col.width = 230 * 20
  22. seven_col.width = 230 * 20
  23. ws.write(0, 0, "id")
  24. ws.write(0, 1, "姓名")
  25. ws.write(0, 2, "性别")
  26. ws.write(0, 3, "身份证号码")
  27. ws.write(0, 4, "电话号码")
  28. ws.write(0, 5, "审核状态")
  29. ws.write(0, 6, "注册时间")
  30. dataw = Volunteer.query.order_by(Volunteer.id).all()
  31. if dataw is not None:
  32. for i in range(0, len(dataw)):
  33. pet = dataw[i]
  34. repairDate = pet.register_time.strftime('%Y-%m-%d %Z %H:%M:%S') if pet.register_time else ''
  35. status = '已审核' if pet.check_status == 1 else '未审核' if pet.check_status == 0 else ''
  36. ws.write(i + 1, 0, pet.id)
  37. ws.write(i + 1, 1, pet.name)
  38. ws.write(i + 1, 2, pet.gender)
  39. ws.write(i + 1, 3, pet.id_card)
  40. ws.write(i + 1, 4, pet.phone)
  41. ws.write(i + 1, 5, status)
  42. ws.write(i + 1, 6, repairDate)
  43. # 创建一个内存中的文件对象
  44. file_obj = io.BytesIO()
  45. wb.save(file_obj)
  46. file_obj.seek(0)
  47. # 创建响应对象
  48. response = make_response(file_obj.getvalue())
  49. # 设置Content-Type和Content-Disposition头信息
  50. response.headers['Content-Type'] = 'application/vnd.ms-excel'
  51. response.headers['Content-Disposition'] = 'attachment; filename="repair.xls"'
  52. return response
第二种:存储在后端然后再返回给前端
  1. import os
  2. import time
  3. import xlwt as xlwt
  4. from flask import send_file, make_response
  5. from flask_backend.models import Volunteer
  6. @volunteer_blue.route('/download_excel', methods=['POST'])
  7. def exportData():
  8. wb = xlwt.Workbook()
  9. ws = wb.add_sheet('志愿者报表')
  10. first_col = ws.col(0) # xlwt中是行和列都是从0开始计算的
  11. second_col = ws.col(1)
  12. third_col = ws.col(2)
  13. four_col = ws.col(3)
  14. five_col = ws.col(4)
  15. six_col = ws.col(5)
  16. seven_col = ws.col(6)
  17. first_col.width = 128 * 20
  18. second_col.width = 230 * 20
  19. third_col.width = 230 * 20
  20. four_col.width = 128 * 20
  21. five_col.width = 230 * 20
  22. six_col.width = 230 * 20
  23. seven_col.width = 230 * 20
  24. ws.write(0, 0, "id")
  25. ws.write(0, 1, "姓名")
  26. ws.write(0, 2, "性别")
  27. ws.write(0, 3, "身份证号码")
  28. ws.write(0, 4, "电话号码")
  29. ws.write(0, 5, "审核状态")
  30. ws.write(0, 6, "注册时间")
  31. dataw = Volunteer.query.order_by(Volunteer.id).all()
  32. if dataw is not None:
  33. for i in range(0, len(dataw)):
  34. pet = dataw[i]
  35. repairDate = pet.register_time.strftime('%Y-%m-%d %Z %H:%M:%S') if pet.register_time else ''
  36. status = '已审核' if pet.check_status == 1 else '未审核' if pet.check_status == 0 else ''
  37. ws.write(i + 1, 0, pet.id)
  38. ws.write(i + 1, 1, pet.name)
  39. ws.write(i + 1, 2, pet.gender)
  40. ws.write(i + 1, 3, pet.id_card)
  41. ws.write(i + 1, 4, pet.phone)
  42. ws.write(i + 1, 5, status)
  43. ws.write(i + 1, 6, repairDate)
  44. now = str(time.time())
  45. path = "/static/excel/"
  46. fileName = "repair_" + now + ".xls"
  47. file_path = os.path.dirname(__file__) + path
  48. if not os.path.exists(file_path):
  49. os.makedirs(file_path)
  50. file_path = file_path + fileName
  51. try:
  52. f = open(file_path, 'r')
  53. f.close()
  54. except IOError:
  55. f = open(file_path, 'w')
  56. wb.save(file_path)
  57. # 创建响应对象
  58. response = make_response(send_file(file_path, as_attachment=True))
  59. # 设置Content-Type和Content-Disposition头信息
  60. response.headers['Content-Type'] = 'application/vnd.ms-excel'
  61. response.headers['Content-Disposition'] = 'attachment; filename="repair.xls"'
  62. return response

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

闽ICP备14008679号