前端实现导出表格

方法一:CsvExportor导出excel表格

一、安装

npm install --save csv-export

二、页面引入

import CsvExportor from 'csv-exportor'

三、导出数据

const exportdata = () => { // 导出方法
	const exportlist = [
		{name:'张三',age:'22',sex:'女',address:'地球'},
		{name:'李四',age:'22',sex:'女',address:'火星'},
		{name:'王五',age:'22',sex:'女',address:'未知'}
	]
	const header = ['姓名', '年龄', '性别', '地址']
	CsvExportor.downloadCsv(exportlist, { header }, '人员登记表.csv')
}

方法二


//vue3
const tableToExcel = (function () {
  /*
   **两个参数
   **table:table的id
   **name:表格名称
   */
   const  mineType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  const template =
      '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
    format = function (s: any, c: any) {
      return s.replace(/{(\w+)}/g, function (m: any, p: any) {
        return c[p];
      });
    };
  return function (table: any, name: any) {
    if (!table.nodeType) table = document.getElementById(table);
    var ctx = { worksheet: name || "Worksheet", table: table.innerHTML };
    download(format(template, ctx), name,mineType);
  };
})();


//vue2

tableToExcel(table, name) {
 const  mineType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  const template =
    '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>';
  const format = function (s, c) {
    return s.replace(/{(\w+)}/g, function (m, p) {
      return c[p];
    });
  };
  if (!table.nodeType) table = document.getElementById(table);
  var ctx = { worksheet: name || "Worksheet", table: table.innerHTML };
  download(format(template, ctx), name,mineType);
}
const download= (data: Blob, fileName: string, mineType: string) => {
  // 创建 blob
  const blob = new Blob([data], { type: mineType });
  // 创建 href 超链接,点击进行下载
  window.URL = window.URL || window.webkitURL;
  const href = URL.createObjectURL(blob);
  const downA = document.createElement("a");
  downA.href = href;
  downA.download = fileName;
  downA.click();
  // 销毁超连接
  window.URL.revokeObjectURL(href);
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值