export js array to csv

How to Export JS Array to CSV File

Most websites require users to be able to export data to CSV. Typically, this is done by sending data to back end server, writing this data to CSV file and triggering a download in user’s browser. But with recent browser developments, you can directly write data to CSV from browser itself, without sending it to back end server. In this article, we will learn how to export JS array to CSV file.


How to Export JS Array to CSV File

Let us say you have the following array in JavaScript.

rows = [
    ["John", "NYC", "some info"],
    ["Joe", "SF", "more info"]
];

Next, we define the CSV content format.

csvContent = "data:text/csv;charset=utf-8,";

Then we format the JS data into CSV format as shown below.

rows.forEach(function(rowArray) {
    let row = rowArray.join(",");
    csvContent += row + "\r\n";
});

In the above code, we are basically converting JS arrays into CSV data where each array’s data is on a separate line, with array items being comma separated. At the end of each line, we add a newline character.

The above method does not allow you to specify the filename of your CSV file but you can always set it before the download begins. If you also want to specify the filename you need to create a hidden anchor tag and set its download attribute

var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "data.csv".
rows.forEach(function(rowArray) {
    let row = rowArray.join(",");
    csvContent += row + "\r\n";
});

Once your data is in required format, you can download CSV file.

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

In this article, we have learnt how to export JS array using JavaScript. You can use this to export array data into CSV files directly from your browser without sending it to web server.

Also read:

How to Convert Unix Timestamp to Datetime in Python
How to Smooth Scroll on Clicking Links
How to Import SQL in MySQL Using Command Line
How to Change Date Format in jQuery UI Date Picker
How to Fix NGINX Bind 0.0.0.0:80 Failed Error

Leave a Reply

Your email address will not be published. Required fields are marked *