前言
其實這個需求不是很常見,一般是后端接口直接返回流文件,前端調接口下載就行,如果不是有某些特殊需求一定要前端處理,還是建議后端處理下😁
先封裝一下生成excel的方法
downfile.js
export default { data() { return {} }, components: {}, created() { }, methods: { downloadFiles(data,type){ this.JSONToExcelConvertor(data.content, type+"報表", data.title); }, JSONToExcelConvertor(JSONData, FileName, ShowLabel) { //先轉化json const arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData; let excel = '<table>'; //設置表頭 let row = "<tr>"; for (let i = 0, l = ShowLabel.length; i < l; i++) { row += "<td>" + ShowLabel[i] + '</td>'; } //換行 excel += row + "</tr>"; //設置數據 for (let i = 0; i < arrData.length; i++) { let row = "<tr>"; for (let index in arrData[i]) { const value = arrData[i][index] === "." ? "" : arrData[i][index]; row += '<td>' + value + '</td>'; } excel += row + "</tr>"; } excel += "</table>"; let excelFile = "<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'>"; excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">'; excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel'; excelFile += '; charset=UTF-8">'; excelFile += "<head>"; excelFile += "<!--[if gte mso 9]>"; excelFile += "<xml>"; excelFile += "<x:ExcelWorkbook>"; excelFile += "<x:ExcelWorksheets>"; excelFile += "<x:ExcelWorksheet>"; excelFile += "<x:Name>"; excelFile += "{worksheet}"; excelFile += "</x:Name>"; excelFile += "<x:WorksheetOptions>"; excelFile += "<x:DisplayGridlines/>"; excelFile += "</x:WorksheetOptions>"; excelFile += "</x:ExcelWorksheet>"; excelFile += "</x:ExcelWorksheets>"; excelFile += "</x:ExcelWorkbook>"; excelFile += "</xml>"; excelFile += "<![endif]-->"; excelFile += "</head>"; excelFile += "<body>"; excelFile += excel; excelFile += "</body>"; excelFile += "</html>"; const uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile); const link = document.createElement("a"); link.href = uri; link.style = "visibility:hidden"; link.download = FileName + ".xls"; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } }
然后在頁面中調用
<template> <div> <button @click="_sendDownloadFilesServer()">下載報表</button> </div> </template> <script> import RecordServer from "@/service/record.service" const recordServer = new RecordServer() import downloadFileMixin from "@/mixins/downfile" //把上面的文件導入 export default{ data(){ return{ } }, mixins:[downloadFileMixin], methods:{ _sendDownloadFilesServer(){ recordServer.sendDownloadFilesServer({ onSuccess:(res)=>{ console.log(res) this.downloadFiles(res,'火車') // 點擊下載文件會下載名為火車報表的excel }, onFailed:(err)=>{ console.log(err) } }) } } } </script>