1:安装xlsx和file-saver

npm install file-saver xlsx  --save

2:创建localExports.js文件

3:直接上代码

import XLSX from 'xlsx';
const FileSaver = require('file-saver');
import { getRandomNum } from '@/utils';
// 本地导出表格
/**
 * 导出Excel文件
 * @param {*} elementName   table组件id名称
 * @param {*} fileName      文件名
 * @description             使用说明
 *                          import { exportsXlsx } from '@/utils/localExports';
 *                          exportsXlsx('idName', '文件名称');
 */

export function exportsXlsx(elementName, fileName) {
  const time = new Date().getTime();
  const random = getRandomNum(100, 1000);
  const wb = XLSX.utils.table_to_book(clearHead(elementName), { raw: true });
  const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
  FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${fileName}${time}-${random}.xlsx`);
}
function clearHead(elementName) {
  const tableDom = document.querySelector('#' + elementName).cloneNode(true);
  const tableHeader = tableDom.querySelector('.el-table__header-wrapper');
  const tableBody = tableDom.querySelector('.el-table__body');
  tableHeader.childNodes[0].append(tableBody.childNodes[1]);
  const headerDom = tableHeader.childNodes[0].querySelectorAll('th');

  // 移除左侧checkbox的节点
  if (headerDom[0].querySelectorAll('.el-checkbox')) {
    headerDom[0].remove();
  }
  for (const key in headerDom) {
    if (headerDom[key].innerText === '操作') {
      headerDom[key].remove();
    }
  }
  // 清理掉checkbox 和操作的button
  const tableList = tableHeader.childNodes[0].childNodes[2].querySelectorAll('td');
  for (let key = 0; key < tableList.length; key++) {
    if (tableList[key].querySelectorAll('.el-checkbox').length > 0 || tableList[key].querySelectorAll('.el-button').length > 0) {
      tableList[key].remove();
    }
  }
  return tableHeader;
}

4:使用方式

<el-table
          id="good"
          v-loading="listLoading"
          :header-cell-style="{ background: '#FAFAFA', color: '#212532' }"
          :data="list"
          tooltip-effect="dark"
          style="width: 100%"
          height="566"
          border
          @selection-change="handleSelectionChange"
        >

import { exportsXlsx } from '@/utils/localExports';
methods:{
  onSearch() {
      exportsXlsx('good', '模拟数据');
    
    },
}

5:good为table组件的id,getRamdomNum方法如下

// 生成随机数
export function getRandomNum(Min, Max) {
  var Range = Max - Min;
  var Rand = Math.random();
  return (Min + Math.round(Rand * Range));
}

Logo

前往低代码交流专区

更多推荐