Skip to content

How to download a CSV file from JavaScript

Last updated on April 4, 2020

In this blog post, I would like to share with you a frequently used feature from the front-end application, How to download a CSV file from JavaScript.

Use Case

The use-case is just as simple as that exporting data to the CSV file. We retrieve the data from the back-end and do download from front-end.

I would like to give you a simple helper function that helps you to download CSV file but from the front-end app.

Code snippet

To explain further, I’ve created one utility method called as downloadCSV.

This method just only accept data which you got from Rest API result most of the time.

function downloadCSV(csvData) {
  let blob = new Blob(["\ufeff" + csvData], {
    type: "text/csv;charset=utf-8;"
  });
  let link = document.createElement("a");
  let url = URL.createObjectURL(blob);
  link.setAttribute("href", url);
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

If you noticed one thing from the above code, we have created anchor tagon the fly and appended to DOM then removing.

Published inAngularFrameworksJavaScriptReact

One Comment

Comments are closed.