前端实现导出excel表格(可直接复制)

9 篇文章 0 订阅

 这里是实现excel表格的方法主要思路如下:

1.此方法只需要后端提供接口来获取需要制作成excel表格的内容;

2.拿到数据先制作表头、表格,将内容加进表格,最后生成表格,直接下载到本地;

// 导出表格
    exportTable() {
      this.loading = true;
      //调用接口
      exportExcel(config)
        .then((res) => {
          const code = res.data.code;
          if (code === 100) {
            let content = res.data.data;   //拿到后端返回的数据
            let Header = [     //制作表头
              { name: "入驻时间", prop: "settlementTime" },
              { name: "交易所", prop: "exchangeName" },
              { name: "ID", prop: "id" },
              { name: "账户名称", prop: "name" },
              { name: "分组名称", prop: "groupName" },
              { name: "策略选择", prop: "tacticsName" },
              { name: "投入资金", prop: "initialCnpital" },
              { name: "总收益", prop: "totalRevenue" },
              { name: "总收益率", prop: "totalProfit" },
              { name: "分成比例", prop: "shareRatio" },
              { name: "商务负责人", prop: "principal" },
              { name: "商务抽成", prop: "rake" },
            ];
            this.createTable(Header, content);   //调用下面的方法来制作表格
          } else {
            this.$message.error(res.data.msg);
          }
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
 
 // 创建表格
    createTable(Header, content) {
      let table = document.createElement("table"); //创建table
      let thead = document.createElement("thead"); //thead
      let tbody = document.createElement("tbody"); //thead
      let tr = document.createElement("tr"); //创建tr
      table.appendChild(thead);
      table.appendChild(tbody);
      thead.appendChild(tr);
      // 创建表头
      Header.forEach((item, index) => {
        let th = document.createElement("th");
        th.innerHTML = item.name;
        tr.appendChild(th);
      });
      // 添加内容
      content.forEach((item) => {
        let tr = document.createElement("tr"); //创建tr
        tbody.appendChild(tr);
        Header.forEach((item2) => {
          let td = document.createElement("td");
          tr.appendChild(td);
        });
      });
     
      let xlsxParam = { raw: true };     // 将表格数据设置为文本格式
      let wb = XLSX.utils.table_to_book(table, xlsxParam);
      /* 获取二进制字符串作为输出 */
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户小蝌蚪自动化上的文件。
          //返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "账目列表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
    },

 ——————分割线——————

以下是补充的其他方法:

方法1:(vue3+elementplus)

<template>
    <div>
        <el-button type="primary" :icon="UploadFilled" :disabled="dis || loading" @click="exportTable">{{ loading ? "导出中.." : "导出"
        }}</el-button>
    </div>
</template>
<script lang="ts" setup>
import Axios from "axios";
import { ref } from 'vue';
import { ElMessage } from "element-plus";
import { UploadFilled } from '@element-plus/icons-vue';
import process from '../api/process';

const props = defineProps({
    dis:{
        type:Boolean,
        default:true
    },
    sendObj: {
        type: Object,
        default: {}
    }
});

let loading = ref(false);

const exportTable = () => {
    loading.value = true;
    Axios({
        method: "post",
        url: process.VITE_APP_BASE_API + "/admin/order/export",
        headers: {
            accessToken: localStorage.getItem('token'),
        },
        data: props.sendObj,
        responseType: "blob",
    })
        .then((res) => {
            if (res.data.type == "application/json") {
                ElMessage.error("导出数据超过1万条记录,请添加筛选条件");
                loading.value = false;
            } else {
                var blob = new Blob([res.data], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
                });
                const fileName = "归集记录列表.xlsx";
                const elink = document.createElement("a");
                if ("download" in elink) {
                    // 非IE下载
                    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);
                    loading.value = false;
                } else {
                    // IE10+下载
                    navigator.msSaveBlob(blob, fileName);
                    loading.value = false;
                }
            }
        })
        .catch(function (error) {
            // 请求失败处理
            console.log(error);
        });
}
</script>

如有问题,欢迎留言!!!

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值