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

 


 

posted on 2019-11-08 15:36  LCFLY  阅读(4294)  评论(0编辑  收藏  举报

导航