前端js匯出excel方法分享
前言
之前寫個js匯出excel的方法,但是發現已經過時了,最近用了一下新的匯出方式,可以用,現在分享一下。vue,react都可以用。原理就是通過table匯出excel
方法一:
通過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, 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[i]) { str += `${exportData[i][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是陣列,就是要匯出的欄位,可以針對匯出的欄位做過濾
方法二:
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[i]) { // 增加\t為了不讓表格顯示科學計數法或者其他格式 str += `<td>${this.showList[i][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資料
以上是我最近用過的2中前端匯出excel的方法。