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';
// 本地导出表格
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));
}
到此这篇关于vue使用file-saver本地文件导出的文章就介绍到这了,更多相关vue file-saver本地文件导出内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!