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

news/2024/7/21 5:25:41 标签: flask, vue.js, 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.niftyadmin.cn/n/5245977.html

相关文章

Apache Kafka CVE-2023-25194(metasploit版)

Step1:用docker搭建环境 Step2:docker查看映射端口 Step3:访问特定端口,然后靶标应用。 Step4:用metasploit进行攻击: 首先,打开metasploit,然后查询需要攻击的板块&#xff0…

Redis 中最常用的数据结构之一:String 数据类型介绍

Redis 大家好,我是香香。 在之前的 Redis 专栏 介绍与安装 Redis,高性能内存数据存储系统 我们介绍到了 Redis 支持多种数据结构,包括字符串、哈希表、列表、集合、有序集合等。 那我们今天来讲讲对 Redis 数据类型 String 的理解&#xff…

【Ajax】发送get请求获取接口数据

编写html实现通过Ajax发送get请求并获取数据 代码实现 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title…

【开源】基于Vue.js的二手车交易系统

文末获取源码&#xff0c;项目编号&#xff1a; S 084 。 \color{red}{文末获取源码&#xff0c;项目编号&#xff1a;S084。} 文末获取源码&#xff0c;项目编号&#xff1a;S084。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 数据中心模块2.2 二手车档案管理模块…

用心整理的免费API集合

快递物流订阅与推送&#xff08;含物流轨迹&#xff09;&#xff1a;【物流订阅与推送、H5物流轨迹、单号识别】支持单号的订阅与推送&#xff0c;订阅国内物流信息&#xff0c;当信息有变化时&#xff0c;推送到您的回调地址。地图轨迹支持在地图中展示包裹运输轨迹。包括顺丰…

利用 Python 进行数据分析实验(五)

一、实验目的 使用Python解决问题 二、实验要求 自主编写并运行代码&#xff0c;按照模板要求撰写实验报告 三、实验步骤 1 爬取并下载当当网某一本书的网页内容&#xff0c;并保存为html格式 2 在豆瓣网上爬取某本书的前50条短评内容并计算评分的平均值(自学正则表达式) …

Boost:asio单io_service,多线程run

io_service相当于注册异步回调的一个上下文环境&#xff0c;而run相当于处理异步io的上下文&#xff08;通常是一个线程&#xff09;。 单io_service&#xff0c;多线程run&#xff0c;相当于多个线程同时来处理注册在一个io_service上的回调&#xff1a; //sio_mth.cpp #inc…

QT----Visual Studio打开.ui文件报错无法打开

问题 在我安装完qt后将它嵌入vs&#xff0c;后新建的文件无法打开ui文件 解决方法 右击ui文件打开方式,添加,程序找到你qt的安装目录里的designer.exe。点击确定再次双击就能够打开。