Export array of object in excel file (JavaScript)

Viewed 8161

I have data stored in JavaScript array like this :

var video= [ ["name1",1,2,3], ["name2",4,54,44], ["name3",212,212,1213], ["name4",32,133,33] ];

How can I save this data in CSV file?

3 Answers

Ciao, I think that export-from-json is the easiest way to do that.

You could write something like:

import exportFromJSON from 'export-from-json'
 
var video = [ ["name1",1,2,3], ["name2",4,54,44], ["name3",212,212,1213], ["name4",32,133,33] ];
const fileName = 'download'
const exportType = 'csv'   //exported type could be text, json, csv, xls, xml
 
exportFromJSON({ video, fileName, exportType })

This is a codepen example.

Export of your data in xls looks like this:

enter image description here

Check this out:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Demo</title>>

    <script>
        var data = [
        ["name1", 1, 2, 3],
        ["name2", 4, 54, 44],
        ["name3", 212, 212, 1213],
        ["name4", 32, 133, 33]
        ];


        function generateCSV() {
            var csv = 'Name, Value1, Value2, Value3\n';
            data.forEach(function(row) {
                csv += row.join(',');
                csv += "\n";
            });

            var hiddenElement = document.createElement('a');
            hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
            hiddenElement.target = '_blank';
            hiddenElement.download = 'data.csv';
            hiddenElement.click();
        }
    </script>
</head>
<body>
    <button onclick="generateCSV()">Download</button> 
</body>
</html>

Here we are creating CSV(Comma Seperated Values) file. MS-Excel can open CSV files easily. Later you can convert these CSV files to XLS or XSLX file easily with the help of MS-Excel or any other Spread sheet program such as OpenOffice Calc.

The simplest thing for this might be to create a CSV file for import into Excel. Something like this might work:

const video= [ ["name1",1,2,3], ["name2",4,54,44], ["name3",212,212,1213], ["name4",32,133,33] ];
const toCsv = arr => arr.map(row => row.join(",")).join("\n");
console.log(toCsv(video));

Generally, it's safer to use a library to produce CSV files like these - or to produce actual Excel files (xlsx or xls). Issues like quotation marks and character escaping will be handled for you this way. See e.g. https://www.npmjs.com/package/export-from-json as described in Giovanni Esposito's answer.

For copy and paste into Excel, TSV (tab separated values) often work well. Something like this:

const video= [ ["name1",1,2,3], ["name2",4,54,44], ["name3",212,212,1213], ["name4",32,133,33] ];
const toTsv = arr => arr.map(row => row.join("\t")).join("\r\n");
console.log(toTsv(video));

Related