nodejs 中間層將文件返回給前端


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

 

 
        
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM