question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Q] How client(React.js) download excel file in NodeJS?

See original GitHub issue

💬 Questions and Help

Hi everyone,

I have two separate projects. Client: React, Server: NodeJS

I create excel on the NodeJS side by submitting a form by React.

I want to download this excel from React side. However, I couldn’t download it.

NodeJS code

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
  workbook.xlsx.write(res)
      .then(function(){
          res.end();
      });

NodeJS return network layer

Screen Shot 2020-12-07 at 19 39 28

First try React.js code

 startDownload(response,"resobyte.xlsx")

function startDownload(file, fileName) {
    const url = window.URL.createObjectURL(new Blob([file]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    link.parentNode.removeChild(link);
}

Second try React.js code

  let blob = new Blob([response], {type: 'vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
            FileSaver.saveAs(blob, 'fileName.xlsx");

The file has been downloaded.

My React Service Call

export const createExcel = async (model) => {
  let response = () => {
      return new Promise(function(resolve, reject) {
        fetch(API_URL + '/api/excel/create', {
          method: 'POST',
          responseType: 'arrayBuffer',
          headers: {
          'Content-Type': 'application/json',
          'x-access-token' : TokenService.getToken()
          },
          body: JSON.stringify(model),
        }).then(response => {
          resolve(response);
        });
      });
    };
    let responseData = await response();
    return responseData;
}

Error open excel file

Screen Shot 2020-12-07 at 19 49 55

Please do not originate issue 37. Because I tried all of them don’t work.

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:2
  • Comments:12

github_iconTop GitHub Comments

4reactions
resobytecommented, Dec 13, 2020

Hi @aksharj,

React.js

export const getExcel = async (id,isSendMail = true) => {
  axios.get(API_URL + '/api/excel/getExcel/'+id+'?isSendMail='+isSendMail, { responseType: 'arraybuffer' , headers: {
    'x-access-token' : TokenService.getToken()
    }})
    .then((response) => {
      const dirtyFileName = response.headers['content-disposition'];
      const regex = /filename[^;=\n]*=(?:(\\?['"])(.*?)\1|(?:[^\s]+'.*?')?([^;\n]*))/;
      var  fileName = dirtyFileName.match(regex)[3];
    
      var blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      fileSaver.saveAs(blob, fileName);
    });
}

Node.js

   res.setHeader('Access-Control-Expose-Headers', "Content-Disposition"); //IMPORTANT FOR React.js content-disposition get Name
   res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
   res.setHeader("Content-Disposition", "attachment; filename=" + fileNameExcel+".xlsx");
    return workbook.xlsx.write(res)
        .then(function(){
            res.end();
        });
      })

You can fix this code.

I used axios and fileSaver. You can use GET method.

Important: responseType :‘arrayBuffer’

3reactions
mudassiriqballcommented, Mar 20, 2021

You can do this by fetch API. I am using Next.js so I have placed my .xslx file into the public folder.

const downloadBulkUploadTemplete = async () => {
    fetch("SpreadsheeName.xlsx", {
        method: 'GET',
    }).then(response => response.blob())
        .then(blob => {
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = "bac.xlsx";
            document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
            a.click();
            a.remove();  //afterwards we remove the element again 
        });
    }
Read more comments on GitHub >

github_iconTop Results From Across the Web

How client(React) download excel file in NodeJS?
I create excel on the NodeJS side by submitting a form by React. I want to download this excel from React side. However,...
Read more >
Node.js Download Excel file example with exceljs - BezKoder
Run the Node.js App with command: node src/server.js . Now you can use browser or a HTTP Client to send GET request to ......
Read more >
How to Excel Export in React JS - Medium
6. Download the excel data. Step 1: Create the react JS project. Using following commands to create a new react JS project. a)...
Read more >
[Q] How Client(React.js) Download Excel File In NodeJS?
7 déc. 2020 · I want to download this excel from React side. However, I couldn't download it. NodeJS code. res.setHeader('Content-Type', 'application/vnd.
Read more >
How client(express) download excel file? · Issue #37 - GitHub
I made it work yesterday. We just has to make sure that the "responseType" on the HTTP Request made by the client was...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found