- 安装xlsx
npm i --save https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz
- 引入xlsx并使用
import XLSX from 'xlsx';
const tableRef = ref<any>(null);
// 导出为 Excel
const exportToExcel = () => {// 获取 el-table 的引用tableRef.value = tableRef.value || document.querySelector('.el-table');// 将 el-table 数据转换为二维数组const dataArray = [];const headers: any = [];tableRef.value.querySelectorAll('.el-table__header-wrapper th').forEach((th: any) => {headers.push(th.textContent.trim());});dataArray.push(headers);tableRef.value.querySelectorAll('.el-table__body-wrapper tbody tr').forEach((row: any) => {const rowData: any = [];row.querySelectorAll('td').forEach((cell: any) => {rowData.push(cell.textContent.trim());});dataArray.push(rowData);});// 创建一个新的工作簿const workbook = XLSX.utils.book_new();// 创建一个新的工作表const worksheet = XLSX.utils.aoa_to_sheet(dataArray);// 将工作表添加到工作簿XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');// 将工作簿保存为 Excel 文件XLSX.writeFile(workbook, '学科分数分布统计.xlsx');
};
补充:html
<template><div class="tableList"><p>统计</p><el-button @click="exportToExcel">导出为Excel</el-button><el-table :data="tableData" border :header-cell-style="headerCellStyle" stripe :cell-style="cellStyle"><el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop" :label="column.label"></el-table-column></el-table></div>
</template>
表格样式设计
const headerCellStyle = {'background-color': '#bdd7ff','borderColor': '#fff','font-weight': 'normal','text-align': 'center','height': '60px'
};const cellStyle = {'borderColor': '#fff','text-align': 'center'
};