简体   繁体   中英

Javascript to CSV Function not compatible with IE or Firefox

I have a function that converts data to csv using javascript. Here is my Fiddle . This however does not work in firefox or Internet explorer. I tried debugging but i am not sure what to look for or where and nothing sticks out clearly. Any help is apprecitated. Thanks

 <body>

 <a href='#' onclick='downloadCSV({ filename: "stock-data.csv" });'>Download CSV</a>

</body>

     var stockData = [
    {
        Symbol: "AAPL",
        Company: "Apple Inc.",
        Price: "132.54"
    },
    {
        Symbol: "INTC",
        Company: "Intel Corporation",
        Price: "33.45"
    },
    {
        Symbol: "GOOG",
        Company: "Google Inc",
        Price: "554.52"
    }
];

function convertArrayOfObjectsToCSV(args) {
    var result, ctr, keys, columnDelimiter, lineDelimiter, data;

    data = args.data || null;
    if (data == null || !data.length) {
        return null;
    }

    columnDelimiter = args.columnDelimiter || ',';
    lineDelimiter = args.lineDelimiter || '\n';

    keys = Object.keys(data[0]);

    result = '';
    result += keys.join(columnDelimiter);
    result += lineDelimiter;

    data.forEach(function(item) {
        ctr = 0;
        keys.forEach(function(key) {
            if (ctr > 0) result += columnDelimiter;

            result += item[key];
            ctr++;
        });
        result += lineDelimiter;
    });

    return result;
}

window.downloadCSV = function(args) {
    var data, filename, link;

    var csv = convertArrayOfObjectsToCSV({
        data: stockData
    });
    if (csv == null) return;

    filename = args.filename || 'export.csv';

    if (!csv.match(/^data:text\/csv/i)) {
        csv = 'data:text/csv;charset=utf-8,' + csv;
    }
    data = encodeURI(csv);

    link = document.createElement('a');
    link.setAttribute('href', data);
    link.setAttribute('download', filename);
    link.click();
};

To download in firefox and ie you have to append it to the body before clicking. Try adding this.

link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

Here's a fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM