nodejs 中间层返回文件给前端

2,718 阅读1分钟

1.通过npm 下载 excel-export 插件
let nodeExcel = require('excel-export');  
2.拿到后台数据之后配置
  let excelConfig ={};  创建对象        excelConfig.name = "mysheet";   //表名        //列名
        excelConfig.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);
          })
          //行数据
          excelConfig.rows = arr;          // console.log('配置信息',excelConfig);
          let res1 = nodeExcel.execute(excelConfig);          res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
          res.setHeader("Content-Disposition", "attachment; filename=" + "Report.csv");
          res.json({code: 1, result: res1});
        }
 3. 前端拿到返回数据之后处理
   const buf = Buffer.from(data, 'binary')
      let blob = new Blob([buf], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
      let downloadElement = document.createElement('a');      let 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