JavaScript array to CSV

后端 未结 9 884
不知归路
不知归路 2020-12-02 06:23

I\'ve followed this post How to export JavaScript array info to csv (on client side)? to get a nested js array written as a csv file.

The array looks like:



        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 07:08

    I created this code for creating a nice, readable csv files:

    var objectToCSVRow = function(dataObject) {
        var dataArray = new Array;
        for (var o in dataObject) {
            var innerValue = dataObject[o]===null?'':dataObject[o].toString();
            var result = innerValue.replace(/"/g, '""');
            result = '"' + result + '"';
            dataArray.push(result);
        }
        return dataArray.join(' ') + '\r\n';
    }
    
    var exportToCSV = function(arrayOfObjects) {
    
        if (!arrayOfObjects.length) {
            return;
        }
    
        var csvContent = "data:text/csv;charset=utf-8,";
    
        // headers
        csvContent += objectToCSVRow(Object.keys(arrayOfObjects[0]));
    
        arrayOfObjects.forEach(function(item){
            csvContent += objectToCSVRow(item);
        }); 
    
        var encodedUri = encodeURI(csvContent);
        var link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "customers.csv");
        document.body.appendChild(link); // Required for FF
        link.click();
        document.body.removeChild(link); 
    }
    

    In your case, since you use arrays in array instead of objects in array, You will skip the header part, but you could add the column names yourself by putting this instead of that part:

    // headers
    csvContent += '"Column name 1" "Column name 2" "Column name 3"\n';
    

    The secret is that a space separates the columns in the csv file, and we put the column values in the double quotes to allow spaces, and escape any double quotes in the values themselves.

    Also note that I replace null values with empty string, because that suited my needs, but you can change that and replace it with anything you like.

提交回复
热议问题