Javascript Export Array To CSV File (Simple Examples)

Welcome to a quick tutorial and examples on how to export an array to a CSV file in Javascript. Need to create a CSV file in your web app? Well, we don’t actually need to send the array to the server. Modern Javascript is fully capable of generating files on the client-side – Read on for the examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Array To CSV Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

HOW CSV FILES WORK

For the beginners, here’s a quick example of a CSV file:

Job,job@doe.com,123456,
Joe,joe@doe.com,234567,
Joi,joi@doe.com,345678,

Yes, CSV files are nothing but simple text files.

  • , Columns are separated with commas.
  • \r\n Rows are separated with newlines.

 

 

JAVASCRIPT ARRAY TO CSV FILE

All right, let us now get into the examples of how to “export” an array to a CSV file in Javascript.

 

1) DOWNLOAD BLOB

1-blob-download.js
function saveCSV () {
  // (A) ARRAY OF DATA
  var array = [
    ["Job", "job@doe.com", "123456"],
    ["Joe", "joe@doe.com", "234567"],
    ["Joi", "joi@doe.com", "345678"],
    ["Jon", "jon@doe.com", "456789"],
    ["Jou", "jou@doe.com", "987654"],
    ["Joy", "joy@doe.com", "876543"],
  ];
 
  // (B) ARRAY TO CSV STRING
  var csv = "";
  for (let row of array) {
    for (let col of row) { csv += col + ","; }
    csv += "\r\n";
  }
 
  // (C) CREATE BLOB OBJECT
  var myBlob = new Blob([csv], {type: "text/csv"});
 
  // (D) CREATE DOWNLOAD LINK
  var url = window.URL.createObjectURL(myBlob);
  var anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = "demo.csv";
 
  // (E) "FORCE DOWNLOAD"
  // NOTE: MAY NOT ALWAYS WORK DUE TO BROWSER SECURITY
  // BETTER TO LET USERS CLICK ON THEIR OWN
  anchor.click();
  window.URL.revokeObjectURL(url);
  anchor.remove();
}

Not going to explain this line-by-line, it should be pretty straightforward once you read through the code:

  • (A & B) A dummy array of users, and we “convert” it into a CSV string.
  • (C) new Blob([csv], {type: "text/csv"}) creates the CSV file. For the uninitiated, Blob is a “raw binary object”.
  • (D & E) Due to security restrictions, client-side Javascript cannot directly save the CSV Blob. Thus this entire “roundabout method” to create a download link, and offer it as a download instead.

 

 

2) FILE STREAM

2-file-stream.js
async function saveCSV () {
  // (A) ARRAY OF DATA
  var array = [
    ["Job", "job@doe.com", "123456"],
    ["Joe", "joe@doe.com", "234567"],
    ["Joi", "joi@doe.com", "345678"],
    ["Jon", "jon@doe.com", "456789"],
    ["Jou", "jou@doe.com", "987654"],
    ["Joy", "joy@doe.com", "876543"],
  ];
 
  // (B) ARRAY TO CSV STRING
  var csv = "";
  for (let row of array) {
    for (let col of row) { csv += col + ","; }
    csv += "\r\n";
  }
 
  // (C) CREATE BLOB OBJECT
  var myBlob = new Blob([csv], {type: "text/csv"});
 
  // (D) FILE HANDLER & FILE STREAM
  const fileHandle = await window.showSaveFilePicker({
    suggestedName : "demo.csv",
    types: [{
      description: "CSV file",
      accept: {"text/csv": [".csv"]}
    }]
  });
  const fileStream = await fileHandle.createWritable();
 
  // (E) WRITE FILE
  await fileStream.write(myBlob);
  await fileStream.close();
}

This is an alternative way to save the generated CSV file, by creating a writable file stream. Take note though – This is not supported on all browsers.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LIMITATIONS

As you can see, we are writing an entire “CSV string” into a blob object. This works fine if you don’t have too many entries to deal with, but it will run into memory and performance issues with massive data. While it is possible to write “line-by-line” with the file stream method, it is not fully supported in all browsers.

 

COMPATIBILITY CHECKS

At the time of writing, the file stream method will not work on Firefox.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Javascript Array To CSV File (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.