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

前端 未结 29 1739
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 21:55

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 loo

29条回答
  •  春和景丽
    2020-11-21 22:38

    I use this function to convert an string[][] to a csv file. It quotes a cell, if it contains a ", a , or other whitespace (except blanks):

    /**
     * Takes an array of arrays and returns a `,` sparated csv file.
     * @param {string[][]} table
     * @returns {string}
     */
    function toCSV(table) {
        return table
            .map(function(row) {
                return row
                    .map(function(cell) {
                        // We remove blanks and check if the column contains
                        // other whitespace,`,` or `"`.
                        // In that case, we need to quote the column.
                        if (cell.replace(/ /g, '').match(/[\s,"]/)) {
                            return '"' + cell.replace(/"/g, '""') + '"';
                        }
                        return cell;
                    })
                    .join(',');
            })
            .join('\n'); // or '\r\n' for windows
    
    }
    

    Note: does not work on Internet Explorer < 11 unless map is polyfilled.

    Note: If the cells contain numbers, you can add cell=''+cell before if (cell.replace... to convert numbers to strings.

    Or you can write it in one line using ES6:

    t.map(r=>r.map(c=>c.replace(/ /g, '').match(/[\s,"]/)?'"'+c.replace(/"/g,'""')+'"':c).join(',')).join('\n')
    

提交回复
热议问题