Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export JavaScript array info to csv (on client side)?

I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which looks like this:

[["name1", "city_name1", ...]["name2", "city_name2", ...]] 

Any idea how I can export this to CSV on the client side?

like image 574
Sam007 Avatar asked Feb 19 '13 16:02

Sam007


People also ask

How do I export a dataset to csv?

Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).

How do I create a CSV file in node?

First, we import the native file system module ( fs ) and the csv-parse module. Then, we create a parser which accepts an object literal, containing the options we'd like to set. The second argument is the callback function that's used to access the records - or just print them out, in our case.


2 Answers

You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):

const rows = [     ["name1", "city1", "some other info"],     ["name2", "city2", "more info"] ];  let csvContent = "data:text/csv;charset=utf-8,";  rows.forEach(function(rowArray) {     let row = rowArray.join(",");     csvContent += row + "\r\n"; }); 

or the shorter way (using arrow functions):

const rows = [     ["name1", "city1", "some other info"],     ["name2", "city2", "more info"] ];  let csvContent = "data:text/csv;charset=utf-8,"      + rows.map(e => e.join(",")).join("\n"); 

Then you can use JavaScript's window.open and encodeURI functions to download the CSV file like so:

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

Edit:

If you want to give your file a specific name, you have to do things a little differently since this is not supported accessing a data URI using the window.open method. In order to achieve this, you can create a hidden <a> DOM node and set its download attribute as follows:
var encodedUri = encodeURI(csvContent); var link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "my_data.csv"); document.body.appendChild(link); // Required for FF  link.click(); // This will download the data file named "my_data.csv". 
like image 163
Default Avatar answered Sep 19 '22 08:09

Default


Based on the answers above I created this function that I have tested on IE 11, Chrome 36 and Firefox 29

function exportToCsv(filename, rows) {     var processRow = function (row) {         var finalVal = '';         for (var j = 0; j < row.length; j++) {             var innerValue = row[j] === null ? '' : row[j].toString();             if (row[j] instanceof Date) {                 innerValue = row[j].toLocaleString();             };             var result = innerValue.replace(/"/g, '""');             if (result.search(/("|,|\n)/g) >= 0)                 result = '"' + result + '"';             if (j > 0)                 finalVal += ',';             finalVal += result;         }         return finalVal + '\n';     };      var csvFile = '';     for (var i = 0; i < rows.length; i++) {         csvFile += processRow(rows[i]);     }      var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });     if (navigator.msSaveBlob) { // IE 10+         navigator.msSaveBlob(blob, filename);     } else {         var link = document.createElement("a");         if (link.download !== undefined) { // feature detection             // Browsers that support HTML5 download attribute             var url = URL.createObjectURL(blob);             link.setAttribute("href", url);             link.setAttribute("download", filename);             link.style.visibility = 'hidden';             document.body.appendChild(link);             link.click();             document.body.removeChild(link);         }     } } 

For example: https://jsfiddle.net/jossef/m3rrLzk0/

like image 34
Xavier John Avatar answered Sep 20 '22 08:09

Xavier John