vue3导出表格(导出成Execl表)

前言:该封装方法适用于后端返回的数据是文档流的时候

1.在utils文件夹中新建exportExecl.js用于封装方法

javascript 复制代码
export const exportExecl = (fn, name, data = {}) => {
    fn(data).then((res) => {
      const content = res;
      const blob = new Blob([content]);
      const fileName = name;
      if ("download" in document.createElement("a")) {
        // 非IE下载
        const elink = document.createElement("a"); // 创建一个a标签
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName);
      }
    });
  };

2.在请求的接口是中添加请求类型(responseType: 'arraybuffer')和请求头(headers)

javascript 复制代码
// 服务项列表的导出
export function serviceItemExport(query) {
  return request({
    url: '/hct-oms/serviceItem/export',
    method: 'get',
    params: query,
    responseType: 'arraybuffer', // 文档流类型
    headers:{ // 请求头
      'Content-Type':'application/x-www-form-urlencoded'
    }
  })
}

3.使用

javascript 复制代码
<el-button type="primary" @click="exportService">导出</el-button>

import { exportExecl } from '@/utils/exportExecl';
import {
  serviceItemExport, // 服务项列表的导出
} from '@/api/serviceItemList/index';
// 导出

const exportService = () => {
  const data = {ids:datas.ids};
  exportExecl(serviceItemExport, '服务项表.xlsx', data);
};
// 参数1:是请求的接口,后端会返回文档流;参数2:导出的文件名称,自己随便定义;参数3:接口需要传递的数据
相关推荐
ly76892 小时前
CSS 从入门到进阶:系统掌握现代网页样式与布局
前端·css
SWAGGY..3 小时前
【C++初阶】:(15)模板进阶--从非类型参数到模板特化与分离编译
java·服务器·前端
YHHLAI3 小时前
从「跑分」到「干活」:Benchmark 与 GPT 5.6 的两种叙事
大数据·前端·人工智能·react.js·前端框架
BigTopOne3 小时前
ArLiveLite 用到的 C++/JNI 技术点
前端
BigTopOne3 小时前
ArLiveLite 技术架构-Lite
前端
BigTopOne3 小时前
ArLiveLite-具体功能
前端
BigTopOne3 小时前
ArLiveLite -具体功能
前端
Sherotree3 小时前
理解 JWT:三段分别是什么
前端·ai·开源
BigTopOne3 小时前
ArLiveLite 用到的 FFmpeg API
前端
小弥儿3 小时前
GPT Image 2 提示词库,把散落的生图提示词变成工程资产
开发语言·javascript·gpt·学习