npm install --save xlsx file-saver
在组件里面引入
import FileSaver from ‘file-saver‘ import XLSX from ‘xlsx‘
第一种 其中#outTable是在el-table上定义的id
exportExcel() { var xlsxParam = { raw: true };//转换成excel时,使用原始的格式 var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);//outTable为列表id var wbout = XLSX.write(wb, { bookType: "xlsx", bookSST: true, type: "array" }); try { FileSaver.saveAs( new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }), "sheetjs.xlsx" ); } catch (e) { if (typeof console !== "undefined") console.log(e, wbout); } return wbout;}
第二种 通过数组导出excel
var _data = [ [ "id", "name", "value" ], [ 1, "sheetjs", 7262 ], [ 2, "js-xlsx", 6969 ] ]; const ws= XLSX.utils.aoa_to_sheet(_data); /* generate workbook and add the worksheet */ const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, ‘Sheet1‘); /* save to file */ XLSX.writeFile(wb, ‘SheetJS.xlsx‘);
第三种通过json导出excel
exportExcel() { var wopts = {
bookType: ‘xlsx‘, bookSST: true, type: ‘binary‘ }; var workBook = { SheetNames: [‘Sheet1‘], Sheets: {}, Props: {} }; var table = []; for(var i=0;i<this.multipleSelection.length;i++){ var params = { 姓名: this.multipleSelection[i].name, 部门: this.multipleSelection[i].department, 职务名称: this.multipleSelection[i].titles, 档案编号:this.multipleSelection[i].fileNum, 校验状态:this.multipleSelection[i].verifyStatus, 审核状态:this.multipleSelection[i].checkedStatus, 备注:this.multipleSelection[i].checkedReason, } table[i] = params }; //1、XLSX.utils.json_to_sheet(data) 接收一个对象数组并返回一个基于对象关键字自动生成的“标题”的工作表,默认的列顺序由使用Object.keys的字段的第一次出现确定 //2、将数据放入对象workBook的Sheets中等待输出 workBook.Sheets[‘Sheet1‘] = XLSX.utils.json_to_sheet(table); //3、XLSX.write() 开始编写Excel表格 //4、changeData() 将数据处理成需要输出的格式 FileSaver.saveAs(new Blob([this.changeData(XLSX.write(workBook, wopts))], {type: ‘application/octet-stream‘}), "sheetjs.xlsx") }, changeData(s) { //如果存在ArrayBuffer对象(es6) 最好采用该对象 if (typeof ArrayBuffer !== ‘undefined‘) { //1、创建一个字节长度为s.length的内存区域 var buf = new ArrayBuffer(s.length); //2、创建一个指向buf的Unit8视图,开始于字节0,直到缓冲区的末尾 var view = new Uint8Array(buf); //3、返回指定位置的字符的Unicode编码 for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } else { var buf = new Array(s.length); for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF; return buf; } },
第三种适合导出选中的数据如果选中的json数据字段都是你需要的可以用下面的方法导出
const workSheet = XLSX.utils.json_to_sheet(this.multipleSelection, { header: [‘列1‘, ‘列2‘, ‘列3‘, ‘列1‘, ‘列2‘, ‘列3‘, ‘列1‘, ‘列2‘], skipHeader: true// 跳过上面的标题行 });const ws = XLSX.utils.aoa_to_sheet(workSheet);const wb = XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb, ws, ‘Sheet1‘); /* save to file */XLSX.writeFile(wb, ‘SheetJS.xlsx‘);
原文地址:https://www.cnblogs.com/dragonKings/p/12155289.html
时间: 2024-11-06 03:24:54