1.通過npm 下載 excel-export 插件 let nodeExcel = require('excel-export'); 2.拿到后台數據之后配置 let conf ={}; 創建對象 conf.name = "mysheet"; //表名 //列名 conf.cols = [ { caption:'SN', type:'string' }, ]; let json = JSON.parse(resp.body).result; // 處理后台返回數據 // 判斷后台返回數據 if(json.length) { let arr = []; //將json數據轉換為二維數組 json.map((item)=>{ let a = []; a.push(item); arr.push(a); }) //行數據 conf.rows = arr; // console.log('配置信息',excelConfig); let res1 = nodeExcel.execute(conf); res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); res.setHeader("Content-Disposition", "attachment; filename=" + "Report.csv"); // res.end(res1, 'binary'); res.json({code: 1, result: res1}); } 3. 前端拿到返回數據之后處理 const buf = Buffer.from(data, 'binary') var blob = new Blob([buf], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet這里表示xlsx類型 var downloadElement = document.createElement('a'); var href = window.URL.createObjectURL(blob); // 創建下載的鏈接 downloadElement.href = href; downloadElement.download = this.form.snBatchCode+'SN.xlsx'; // 下載后文件名 document.body.appendChild(downloadElement); downloadElement.click(); // 點擊下載 document.body.removeChild(downloadElement); // 下載完成移除元素 window.URL.revokeObjectURL(href); // 釋放掉blob對象 參考: https://developer.mozilla.org/zh-CN/docs/Web/API/Blob