方案1

纯原生js在页面实现 导出 .xls格式

toContentPrintExcel22(e) {// 获取页面内容this.name = this.$t(this.selectReport.name);// 打印内容部分-区分类型,利润和其他let tableHtml = document.querySelectorAll('#excelContent table')[0].innerHTML;// 创建a标签const linkNode = document.createElement('a');linkNode.download = this.name;linkNode.style.display = 'none';// 利用Blob对象将字符内容转变成二进制数据const exportHtml = `Titlefont-family: 宋体;table{text-align:center;}
${tableHtml}
`;const blob = new Blob([exportHtml], { type: 'application/vnd.ms-excel' });linkNode.href = URL.createObjectURL(blob);// 点击document.body.appendChild(linkNode);linkNode.click();// 移除document.body.removeChild(linkNode);},

方案2(推荐,xlsx格式兼容office)

安装vue组件 xlsx

1. 环境

npm install xlsx

2. 模块中引入

import * as XLSX from ‘xlsx’;

3. 代码调用

exportExcel(filename) {const xlsxParam = { raw: true }; // 导出的内容只做解析,不进行格式转换// excelContent,table外层的id名const workbook = XLSX.utils.table_to_book(document.getElementById('excelContent'), xlsxParam);// 自带的快捷写法 XLSX.writeFileXLSX.writeFile(workbook, filename + '.xlsx');},

方案3

安装vue组件 xlsx, file-saver

1. 环境

npm install xlsx

npm install file-saver

2. 模块中引入

import * as XLSX from ‘xlsx’;

import FileSaver from ‘file-saver’;

3. 代码调用

exportExcel(filename) {const xlsxParam = { raw: true }; // 导出的内容只做解析,不进行格式转换const workbook = XLSX.utils.table_to_book(document.getElementById('excelContent'), xlsxParam);/* 获取二进制字符进行输出 */// 使用组件FileSaver的写法const wbOut = XLSX.write(wb, {bookType: 'xlsx',bookSST: true,type: 'array'});try {FileSaver.saveAs(new Blob([wbOut], { type: 'application/octet-stream' }),filename + '.xlsx');} catch (e) {if (typeof console !== 'undefined') {console.log(e, wbOut);}}return wbOut;},

拓展: 多张 sheet 导出

 exportMultiExcel(filename) {const xlsxParam = { raw: true };// 转换成excel时,使用原始的格式,这样导出的时候数字过长不会变成科学计数法const workbook = XLSX.utils.book_new();// 这里开始添加多个sheet页 - 用于报表-销售-利润页面const ws1 = XLSX.utils.table_to_sheet(document.querySelector('#revenue1'), xlsxParam);XLSX.utils.book_append_sheet(workbook, ws1, 'sheet1');const ws2 = XLSX.utils.table_to_sheet(document.querySelector('#revenue2'), xlsxParam);XLSX.utils.book_append_sheet(workbook, ws2, 'sheet2');const ws3 = XLSX.utils.table_to_sheet(document.querySelector('#revenue3'), xlsxParam);XLSX.utils.book_append_sheet(workbook, ws3, 'sheet3');XLSX.writeFile(workbook, filename + '.xlsx');}