exceljs - 为什么 workbook.xlsx.write(res) 没有下载文件?

问题描述

我有一个 MEAN 项目。下面是节点后端的代码,用于使用 exceljs 库下载 excel 文件中的过滤集合。代码不会抛出任何错误。但是,它不会下载文件。我哪里出错了?

节点控制器方法

const exportSelection = {_id: 0,__v: 0,compId: 0,execId: 0,payts: 0}

exports.exportServLog = async (req,res,next) => {
  const serviceLog = await ServiceLog.find().select(exportSelection);

  const rows = await servLogService.transformRows(serviceLog); // method defined in service - see below

  const columns = [
    {name:'servNumber'},{name:'servPeriod',filterButton: true},// ...more columns...
    {name:'fees',totalsRowFunction: 'custom',totalsRowFormula: `SUBTOTAL(109,E2:E${rows.length + 1})`},// ...more columns...
    {name:'remarks'}
  ];

  // creating a workbook
  let wb = new excel.Workbook();
  wb.creator = 'myApp';
  wb.lastModifiedBy = 'myApp';
  wb.created = new Date();
  wb.modified = new Date();

  // adding worksheet to the workbook
  let ws = wb.addWorksheet('ServiceLog',{views:[{state: 'frozen',xSplit: 0,ySplit: 1}] });
  ws.state = 'visible';
  ws.properties.defaultColWidth = 30;

  // adding table to worksheet
  ws.addTable({
    name: 'ServiceLog',ref: 'A1',headerRow: true,totalsRow: false,style: {
      theme: 'TableStyleLight1',showFirstColumn: true,showRowStripes: true
    },columns: columns,rows: [...rows]
  });

  // adding password to worksheet
  await ws.protect('password');

  fileName="ServiceLog.xlsx"
  
  res.setHeader('Content-Type','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  res.setHeader("Content-Disposition","attachment; filename=" + fileName);

  /// await wb.xlsx.write(res);  changed this line with the below
  wb.xlsx.writeFile("./ServiceLog.xlsx").then(
    (response) => {
      console.log("File is created");
      console.log(path.join(__dirname,"../ServiceLog.xlsx"));
      res.sendFile(path.join(__dirname,"../ServiceLog.xlsx"));
    },(err) => {
      console.log("ERROR: ",err);
    }
  );

  res.end();
}

我已经检查了使用 console.log 生成的行。而且看起来还不错。

服务中的transformRows辅助方法

function transformRows(servLog){
  const transformedRows = servLog.map(row => {
    let tRow = [];
    tRow.push(row._doc['servNumber']);
    tRow.push(row._doc['servPeriod']);
    // ...more rows...
    tRow.push(row._doc['remarks']);

    return tRow;
  });
  return transformedRows;
}
//there are some undefined items in each row. Hope that's not an issue.

Angular Service http 调用

  downloadServLog(){
    return this.httpClient.get(`${this.reqUrl}/downloadservlog`,{responseType: 'blob'});
  }

组件订阅方式

  onDownloadServLog(){
    this.serviceLogService.downloadServLog()
      .subscribe(
        res => {
          console.log("Are we getting here?",res);
          this.isLoading = false;
          let url = window.URL.createObjectURL(res);  
                       // get error when I use res.data here

          let a = document.createElement('a');
          document.body.appendChild(a);
          a.setAttribute('style','display: none');
          a.href = url;
          a.download = "ServiceLog.xlsx";
          a.click();
          window.URL.revokeObjectURL(url);
          a.remove();
        },(err) => {
          console.log("Is there any error?",err); // This is displayed in console

          this.isLoading = false;
        }
      );
  }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)