方法一: 通过csv的方式导出
exportExcel() { // 前端导出excel const types = { 'DYNAMIC': '动态创意', 'STATIC': '静态创意', 'VIDEO': '视频创意', 'MATERIAL': '素材创意' } let currentGroup = '' let exportData = this.showList.map(item => { if (item.currentGroup) { currentGroup = item.currentGroup } return { creativeId: item.creativeId, creativeName: item.creativeName, description: item.description&& item.description.replace(/[\n\t\r,]/g,";"),// 把里面的回车和中文逗号换成分号 creativeSize: `${item.creativeWidth}*${item.creativeHeight}`, creativeTime: this.getTime(item.startDate) + ' - ' + this.getTime(item.endDate), creativesourceTyle: this.showType(item.creativeSource), creativeTypename: types[item.creativeType] } }) // console.log(exportData) let str = '创意ID,创意名称,创意描述,创意尺寸,创意时间,创意来源,创意类型\n' for (let i = 0; i < exportData.length; i++) { for (let item in exportData) { str += `${exportData[item] + '\t'},` } str += '\n' } // encodeURIComponent解决中文乱码 let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str) // 通过创建a标签实现 var link = document.createElement('a') link.href = uri // 对下载的文件命名 let nowTime = `${new Date().getFullYear()}${(new Date().getMonth() + 1)}${new Date().getDate()}` link.download = `${currentGroup}-${nowTime}.csv` document.body.appendChild(link) link.click() document.body.removeChild(link) }, 注:getTime()和showType()都是转换函数,和主流程不搭噶。showList是数组,就是要导出的字段,可以针对导出的字段做过滤
另外需要注意的是,字段里面不能有中文逗号,换行等,可以用replace去除掉
方法二: base64(s) { return window.btoa(unescape(encodeURIComponent(s))) }, exportExcel() { // 前端导出excel console.log(this.showList) let str = '<tr><td>代理名称</td><td>allianceid</td><td>attachmentFileId</td>' for (let i = 0; i < this.showList.length; i++) { str += '<tr>' for (let item in this.showList) { // 增加\t为了不让表格显示科学计数法或者其他格式 str += `<td>${this.showList[item] + '\t'}</td>` } str += '</tr>' } let worksheet = 'Sheet1' let uri = 'data:application/vnd.ms-excel;base64,' // 下载的表格模板数据 let 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>${str}</table></body></html>` // 下载模板 window.location.href = uri + this.base64(template) },//showList是table数据
原文地址: https://www.haorooms.com/post/js_exportexcel_fx_2019 |
|