JS table下载
时间紧任务重推荐第一种,直接把表格整个拿过来;第二种根据表格的配置和数据进行设置
1、html下载,原生JS
downTable(name) { const uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>', base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) } //el-table表格设置列浮动,会多出一个隐藏table,需要过滤掉 const table = document.getElementById('table')?.innerHTML.replace(/<div class="el-table__fixed".*>[\s\S]*?<\/div>/img, ""); const ctx = {worksheet: name || 'Worksheet', table} // 通过创建a标签实现 const link = document.createElement("a"); link.href = uri + base64(format(template, ctx)); // 对下载的文件命名 link.download = name + '.xlsx'; link.click(); }
优点:快
缺点:时间会被转义,样式会受页面CSS影响,测试反映有的电脑打开慢或文件损坏
2.1、XLSX-通过json数据转成一个worksheet对象
async downTable(type: number) { let tableColumn: any[] = [], tableData: any[] = [], fileName = ''; if (type === 1) { tableColumn = this.trendSaleColumn; tableData = this.trendSaleData; fileName = '售前介入趋势(销售).xlsx'; }else if (type === 3) { await this.getPreSalesConvertInfo(this.transferSaleType, 1); tableColumn = this.transferSaleColumn; tableData = this.transferSaleData; fileName = '售前部门转化(销售).xlsx'; } let data: any[] = [[]]; tableColumn.forEach((item: any) => { data[0].push(item.label); }) tableData.forEach((item: any) => { let row: any[] = []; tableColumn.forEach((column: any) => { row.push(item[column.prop]); }) data.push(row); }) const sheet = XLSX.utils.aoa_to_sheet(data);
//合并单元格配置,需要计算需要合并的行列数 if (type === 3 || type === 4) { if (this.productType[1] > 0 && this.productType[2] > 0) { sheet['!merges'] = [ {s: {r: 1, c: 0}, e: {r: this.productType[1], c: 0}},//s表示开始,e表示结束,r表示行,c表示列; {s: {r: this.productType[1] + 1, c: 0}, e: {r: this.productType[2], c: 0}} ]; } else if (this.productType[1] > 0 || this.productType[2] > 0) { sheet['!merges'] = [ {s: {r: 1, c: 0}, e: {r: this.productType[1] || this.productType[2], c: 0}},//s表示开始,e表示结束,r表示行,c表示列; ]; } } // 通过创建a标签实现 const link = document.createElement("a"); link.href = URL.createObjectURL(sheet2blob(sheet)); // 对下载的文件命名 link.download = fileName; link.click(); }
sheet2blob(sheet: any, sheetName: string = 'sheet1') { const workbook: any = { SheetNames: [sheetName], Sheets: {} }; workbook.Sheets[sheetName] = sheet; // 生成excel的配置项 const wopts: any = { bookType: 'xlsx', // 要生成的文件类型 bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性 type: 'binary' }; const wbout = XLSX.write(workbook, wopts); const blob = new Blob([s2ab(wbout)], {type: "application/octet-stream"}); // 字符串转ArrayBuffer function s2ab(s: any) { const buf = new ArrayBuffer(s.length); const view = new Uint8Array(buf); for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } return blob; }
优点:单元格内容可控,可以设置单元合并等XLSX支持的配置
缺点:复杂表格需要计算合并单元格的位置和数量,比如多级表头
2.2、XLSX-把页面上已有的表格dom节点传入
downTable() { const table = document.getElementById('table')?.innerHTML.replace(/<div class="el-table__fixed".*>[\s\S]*?<\/div>/img, ""); const tableDom = document.createElement('div'); tableDom.innerHTML = table; let ws = XLSX.utils.table_to_sheet(tableDom) //创建一个workbook对象 let wb = XLSX.utils.book_new() //把worksheet对象添加进workbook对象,第三个参数是excel中sheet的名字 XLSX.utils.book_append_sheet(wb, ws, 'sheet1') //接下来就是写入,下载导出 let wb_out = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'}) const blob = new Blob([s2ab(wb_out)], {type: "application/octet-stream"}); // 字符串转ArrayBuffer function s2ab(s: any) { const buf = new ArrayBuffer(s.length); const view = new Uint8Array(buf); for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } // 通过创建a标签实现 const link = document.createElement("a"); link.href = URL.createObjectURL(blob); // 对下载的文件命名 link.download = this.title + '.xlsx'; link.click(); }