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

前端 未结 29 1713
没有蜡笔的小新
没有蜡笔的小新 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:33

    Create a blob with the csv data .ie var blob = new Blob([data], type:"text/csv");

    If the browser supports saving of blobs i.e if window.navigator.mSaveOrOpenBlob)===true, then save the csv data using: window.navigator.msSaveBlob(blob, 'filename.csv')

    If the browser doesn't support saving and opening of blobs, then save csv data as:

    var downloadLink = document.createElement('');
    downloadLink.attr('href', window.URL.createObjectURL(blob));
    downloadLink.attr('download', filename);
    downloadLink.attr('target', '_blank');
    document.body.append(downloadLink);
    

    Full Code snippet:

    var filename = 'data_'+(new Date()).getTime()+'.csv';
    var charset = "utf-8";
    var blob = new Blob([data], {
         type: "text/csv;charset="+ charset + ";"
    });
    if (window.navigator.msSaveOrOpenBlob) {
         window.navigator.msSaveBlob(blob, filename);
    } else {
        var downloadLink = document.element('');
        downloadLink.attr('href', window.URL.createObjectURL(blob));
        downloadLink.attr('download', filename);
        downloadLink.attr('target', '_blank');  
        document.body.append(downloadLink); 
        downloadLink[0].click(); 
    }
    

提交回复
热议问题