当前位置: 首页 > article >正文

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

 前段部分:
1.分装api:在 src/api/volunteer.js文件内
注意:一定要加上" responseType: 'blob' "否则打开文件后是乱码或者根本打不开文件
import request from "@/utils/request";


//导出
export function importVolunteer(data) {
    return request({
        method: 'post',
        url: '/volunteer/download_excel',
        data,
        responseType: 'blob'
    })
}
2. 调用接口 :在src/views/volunteer.vue文件内
 // 导出按钮点击事件处理
    async importHandle() {
      try {
        // 调用导出的接口
        const res = await importVolunteer();
        // 处理导出的Excel文件

        const blob = new Blob([res], {type:'application/vnd.ms-excel;charset=utf-8'});
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');

        link.href = url;
        link.setAttribute('download', '志愿者导出表');
        document.body.appendChild(link);
        link.click();

        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error(error);
      }
    }
后端部分:
第一种:不存储在后端直接返回给前端
import io

import xlwt as xlwt
from flask import  make_response

from flask_backend.models import Volunteer


@volunteer_blue.route('/download_excel', methods=['POST'])
def exportData():
    wb = xlwt.Workbook()
    ws = wb.add_sheet('志愿者报表')
    first_col = ws.col(0)  # xlwt中是行和列都是从0开始计算的
    second_col = ws.col(1)
    third_col = ws.col(2)
    four_col = ws.col(3)
    five_col = ws.col(4)
    six_col = ws.col(5)
    seven_col = ws.col(6)
    first_col.width = 128 * 20
    second_col.width = 230 * 20
    third_col.width = 230 * 20
    four_col.width = 128 * 20
    five_col.width = 230 * 20
    six_col.width = 230 * 20
    seven_col.width = 230 * 20
    ws.write(0, 0, "id")
    ws.write(0, 1, "姓名")
    ws.write(0, 2, "性别")
    ws.write(0, 3, "身份证号码")
    ws.write(0, 4, "电话号码")
    ws.write(0, 5, "审核状态")
    ws.write(0, 6, "注册时间")
    dataw = Volunteer.query.order_by(Volunteer.id).all()
    if dataw is not None:
        for i in range(0, len(dataw)):
            pet = dataw[i]
            repairDate = pet.register_time.strftime('%Y-%m-%d %Z %H:%M:%S') if pet.register_time else ''
            status = '已审核' if pet.check_status == 1 else '未审核' if pet.check_status == 0 else ''
            ws.write(i + 1, 0, pet.id)
            ws.write(i + 1, 1, pet.name)
            ws.write(i + 1, 2, pet.gender)
            ws.write(i + 1, 3, pet.id_card)
            ws.write(i + 1, 4, pet.phone)
            ws.write(i + 1, 5, status)
            ws.write(i + 1, 6, repairDate)


    # 创建一个内存中的文件对象
    file_obj = io.BytesIO()
    wb.save(file_obj)
    file_obj.seek(0)

    # 创建响应对象
    response = make_response(file_obj.getvalue())

    # 设置Content-Type和Content-Disposition头信息
    response.headers['Content-Type'] = 'application/vnd.ms-excel'
    response.headers['Content-Disposition'] = 'attachment; filename="repair.xls"'

    return response
第二种:存储在后端然后再返回给前端
import os
import time

import xlwt as xlwt
from flask import send_file, make_response

from flask_backend.models import Volunteer


@volunteer_blue.route('/download_excel', methods=['POST'])
def exportData():
    wb = xlwt.Workbook()
    ws = wb.add_sheet('志愿者报表')
    first_col = ws.col(0)  # xlwt中是行和列都是从0开始计算的
    second_col = ws.col(1)
    third_col = ws.col(2)
    four_col = ws.col(3)
    five_col = ws.col(4)
    six_col = ws.col(5)
    seven_col = ws.col(6)
    first_col.width = 128 * 20
    second_col.width = 230 * 20
    third_col.width = 230 * 20
    four_col.width = 128 * 20
    five_col.width = 230 * 20
    six_col.width = 230 * 20
    seven_col.width = 230 * 20
    ws.write(0, 0, "id")
    ws.write(0, 1, "姓名")
    ws.write(0, 2, "性别")
    ws.write(0, 3, "身份证号码")
    ws.write(0, 4, "电话号码")
    ws.write(0, 5, "审核状态")
    ws.write(0, 6, "注册时间")
    dataw = Volunteer.query.order_by(Volunteer.id).all()
    if dataw is not None:
        for i in range(0, len(dataw)):
            pet = dataw[i]
            repairDate = pet.register_time.strftime('%Y-%m-%d %Z %H:%M:%S') if pet.register_time else ''
            status = '已审核' if pet.check_status == 1 else '未审核' if pet.check_status == 0 else ''
            ws.write(i + 1, 0, pet.id)
            ws.write(i + 1, 1, pet.name)
            ws.write(i + 1, 2, pet.gender)
            ws.write(i + 1, 3, pet.id_card)
            ws.write(i + 1, 4, pet.phone)
            ws.write(i + 1, 5, status)
            ws.write(i + 1, 6, repairDate)
    now = str(time.time())
    path = "/static/excel/"
    fileName = "repair_" + now + ".xls"
    file_path = os.path.dirname(__file__) + path
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    file_path = file_path + fileName
    try:
        f = open(file_path, 'r')
        f.close()
    except IOError:
        f = open(file_path, 'w')
    wb.save(file_path)


    # 创建响应对象
    response = make_response(send_file(file_path, as_attachment=True))

    # 设置Content-Type和Content-Disposition头信息
    response.headers['Content-Type'] = 'application/vnd.ms-excel'
    response.headers['Content-Disposition'] = 'attachment; filename="repair.xls"'

    return response


http://www.kler.cn/news/161483.html

相关文章:

  • HTTP不同场景下的通信过程和用户上网认证过程分析
  • labelme等标注工具/数据增强工具输出JSON文件格式检查脚本
  • 用友NC word.docx接口存在任意文件读取漏洞
  • git的使用:基础配置和命令行
  • 智能优化算法应用:基于社交网络算法无线传感器网络(WSN)覆盖优化 - 附代码
  • Linux篇:进程间通信
  • [linux进程控制]进程替换
  • class036 二叉树高频题目-上-不含树型dp【算法】
  • java设计模式学习之【组合模式】
  • hql面试题之字符串使用split分割,并选择其中的一部分字段的问题
  • /usr/bin/ld: cannot find -ltinfo 的解决方法
  • 第二十一章——网络通信
  • 使用Jython将Python代码转换为Java可执行文件
  • 手把手将Visual Studio Code变成Python开发神器
  • RabbitMQ 的七种消息传递形式
  • 结构体对齐和补齐
  • HarmonyOS开发(十):通知和提醒
  • 洛谷P1044 [NOIP2003 普及组] 栈 递归方法
  • JVM中 Minor GC 和 Full GC 的区别
  • React中的空标签与Fragment标签的区别
  • 【数据库设计和SQL基础语法】--表的创建与操作--插入、更新和删除数据
  • Nginx(配置SLL证书)
  • 重生奇迹mu武器镶嵌顺序
  • MySQL学习day05
  • C++ STL容器与常用库函数
  • 一则广告,一个故事,这就我选择学习计算机专业的两个原因
  • 中国证券交易所有哪些
  • vs2022 winform 使用LiveCharts.Wpf控件出现黑框 去除方法
  • zabbix分布式监控平台从IPV4切换到IPV6之监控主机切换
  • 【LeeCode】1.两数之和