How to Download a CSV File Using Javascript

Ever wanted to generate a CSV (comma separated values) file directly from the browser, using Javascript? Instead of going to the server..

Look no further!

Create a function to download a csv file

function downloadCsv(csvData: string, filename: string) {
      const blob = new Blob(['\ufeff' + csvData], {
        type: 'text/csv;charset=utf-8;'
      });
      const dwldLink = document.createElement("a");
      const url = URL.createObjectURL(blob);
      const isSafariBrowser = navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1;

      //if Safari open in new window to save file with random filename.
      if (isSafariBrowser)
        dwldLink.setAttribute("target", "_blank");
      
      dwldLink.setAttribute("href", url);
      dwldLink.setAttribute("download", filename+ ".csv");
      dwldLink.style.visibility = "hidden";
      document.body.appendChild(dwldLink);
      dwldLink.click();
      document.body.removeChild(dwldLink);
}

How to use our function

// define some data
const data = 'Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8\n' +
             '12345,abc.de,AB1234567890,USD,01-Jan-21,100,10000000,1.23\n' +
             '12345,abc.de,AB1234567890,USD,01-Jan-21,100,10000000,\n' +
             '12345,abc.de,AB1234567890,USD,01-Jan-21,100,';

// define a file name
const file = 'OurFile';

// use the function
downloadCsv(data, file);