美文网首页
使用nodeJS导出excel

使用nodeJS导出excel

作者: 来了啊小老弟 | 来源:发表于2020-03-24 18:02 被阅读0次

    node部分

      download:app.get('/download', (req,res)=>{
        var delSql = 'DELETE FROM user where id= ?';
        connection.query(delSql,[req.body[0]], function (err, result) {
          if(err){
            console.log('[DELETE ERROR] - ',err.message);
            return;
          }        
          var conf ={};
          conf.name = "mysheet";
          conf.cols = [{
          caption:'string',
              type:'string',
        },{
          caption:'date',
          type:'date',
        },{
          caption:'bool',
          type:'bool'
        },{
          caption:'number',
           type:'number'                
          }];
          conf.rows = [
           ['pi', new Date(Date.UTC(2013, 4, 1)), true, 3.14],
           ["e", new Date(2012, 4, 1), false, 2.7182],
              ["M&M<>'", new Date(Date.UTC(2013, 6, 9)), false, 1.61803],
              ["null date", null, true, 1.414]  
          ];
          var result = nodeExcel.execute(conf);
          //不加这行代码前端获取不到Content-Disposition,前端只能默认获取content-type等几个默认的属性
          res.header('Access-Control-Expose-Headers', 'Content-Disposition');
          res.setHeader('Content-Type', 'application/vnd.ms-excel;charset=UTF-8');
          res.setHeader('Content-Disposition', 'attachment; filename=Report.xlsx');
          res.end(result, 'binary');
        });
      }),
    

    前端部分

    封装了一个axios方法,关键是设置

    responseType: 'blob'

      getParamsDownload: (obj) => {
        // let loading = Loading.service(loadingOPtions)
        return new Promise(function (resolve, reject) {
          let { url, params = '' } = obj
          return instance.get(url, { params: params,responseType: 'blob' }).then(res => {
            if (res) {
              resolve(res)
            }
          }).catch((e) => {
            console.log(e)
          }).finally(() => {
            // loading.close()
          })
        })
      },
    
        download(){
          let _this = this
          var obj = {
            url: this.$urlConfig.download
          }
          this.$api.getParamsDownload(obj).then(function (res) {
            let fileName = res.headers["content-disposition"].split(";")[1].split("filename=")[1];
            let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = window.URL.createObjectURL(blob);
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          })
        },
    

    相关文章

      网友评论

          本文标题:使用nodeJS导出excel

          本文链接:https://www.haomeiwen.com/subject/evkayhtx.html