简体   繁体   English

使用 ExcelJS 和节点 js 下载 excel 文件未在任何浏览器中下载

[英]Downloading excel file using ExcelJS and node js not being downloaded in any browser

I was trying to send .xlsx file using exceljs and nodejs to the client as a downloadable file.我试图使用exceljsnodejs.xlsx文件作为可下载文件发送到客户端。 So far I'm able to create employees.xlsx file but it's not triggering save file dialog in the browser.到目前为止,我能够创建employees.xlsx文件,但它没有触发浏览器中的保存文件对话框。 Here's what I've tried in my backend API:这是我在后端 API 中尝试过的:

My Controller:我的 Controller:

exports.exportEmployees = async (req, res) => {

  try {
    const employees = await Employee.find();
    let workbook = new Excel.Workbook();
    let worksheet = workbook.addWorksheet("Employees");
    worksheet.columns = [
      { header: "Employee Name", key: "fullName", width: 40 },
      { header: "Department", key: "departmentName", width: 25 },
      { header: "Position", key: "positionName", width: 25 },
    ];

    worksheet.addRows(employees);

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

    // This doesn't work either
    // workbook.xlsx.write(res).then(function () {
    //   res.status(200).end();
    // });

    workbook.xlsx.writeFile("./employees.xlsx").then(
      (response) => {
        console.log("File is created"); // I'm able to see this in my console
        console.log(path.join(__dirname, "../employees.xlsx"));
        res.sendFile(path.join(__dirname, "../employees.xlsx"));
      },
      (err) => {
        console.log("ERROR: ", err);
      }
    );
  } catch (err) {
    res.status(500).json({ errors: err });
  }
};

And in my route.js在我的 route.js 中

router.get("/employee-excel", auth, exportExcelController.exportEmployees);

module.exports = router;

So, the problem I'm facing now is whenever I call the api from my Angular app the browser response is a binary code.所以,我现在面临的问题是,每当我从我的 Angular 应用程序调用 api 时,浏览器响应都是二进制代码。

Angular service to call the API Angular服务调用API

generateEmployeeExcel(query: any): Observable<any> {
    return this.http.get(`${this.serverReportAPI}/employee-excel`, {
      params: query,
      headers: this.tokenHelperService.getAuthToken().headers,
    });
  }

My component我的组件

this.reportService.generateEmployeeExcel(query).subscribe(
  (response) => {
    console.log("Are we getting here?", response); // not able to get here
    this.isLoading = false;
  },
  (err) => {
    console.log("Is there any error?", err); // This is displayed in console

    this.isLoading = false;
  }
);

Any help would be appreciated.任何帮助,将不胜感激。

The response in my browser我浏览器中的响应在此处输入图像描述

Change http code to:-将 http 代码更改为:-

generateEmployeeExcel(query: any): Observable<any> {
    return this.http.get(`${this.serverReportAPI}/employee-excel`, {
      params: query,
      headers: this.tokenHelperService.getAuthToken().headers,
      responseType: 'blob'
    });
  }

For subscribe and download:-订阅和下载:-

this.reportService.generateEmployeeExcel(query).subscribe(
  (res) => {
        console.log("Are we getting here?", res); // not able to get here
        this.isLoading = false;
        let url = window.URL.createObjectURL(res.data);
        let a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display: none');
        a.href = url;
        a.download = "employee.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;
  }
);

If support for IE is required:-如果需要支持 IE:-

this.reportService.generateEmployeeExcel(query).subscribe(
  (res) => {
        console.log("Are we getting here?", res); // not able to get here
     if(window.navigator.msSaveBlob) {
         window.nagigator.msSaveBlob(res, "employee.xlsx");
         return;
     }
        this.isLoading = false;
        let url = window.URL.createObjectURL(res.data);
        let a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display: none');
        a.href = url;
        a.download = "employee.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;
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM