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

相关推荐

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

    2023-12-11 12:24:03       42 阅读
  2. fastapi+vue实现导入Excel表格功能

    2023-12-11 12:24:03       17 阅读
  3. Excel表格导入/导出数据工具类

    2023-12-11 12:24:03       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-11 12:24:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-11 12:24:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-11 12:24:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-11 12:24:03       20 阅读

热门阅读

  1. C/C++---------------LeetCode第509. 斐波那契数

    2023-12-11 12:24:03       29 阅读
  2. Node顶级框架-----Express....

    2023-12-11 12:24:03       38 阅读
  3. 做题笔记:SQL Sever 方式做牛客SQL的题目--SQL212

    2023-12-11 12:24:03       36 阅读
  4. 阿里云服务器环境配置,ssh免密登录和配置docker

    2023-12-11 12:24:03       42 阅读
  5. 【网络编程】-- 04 UDP

    2023-12-11 12:24:03       39 阅读
  6. ARM Cortex-M安全之MPU介绍

    2023-12-11 12:24:03       31 阅读
  7. OD机考真题搜集:服务失效判断

    2023-12-11 12:24:03       41 阅读