Javascript - Download CSV as File

后端 未结 4 737
日久生厌
日久生厌 2020-12-28 17:54

I\'m messing with some javascript to download some csv text:



        
4条回答
  •  醉话见心
    2020-12-28 18:11

    Updated Andrew's Answer to avoid using a deprecated function.

    source: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#The_old-fashioned_way

    //Triggers a download of the given file
    //@see https://stackoverflow.com/questions/21177078/javascript-download-csv-as-file
    //@see https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#The_old-fashioned_way
    //
    //@param fileName {string} - Name of the file to download include file extension
    //@param urlData {string} - Encoded URI of the document data
    function downloadFile(fileName, urlData) {
    
        var aLink = document.createElement('a');
        aLink.download = fileName;
        aLink.href = urlData;
    
        var event = new MouseEvent('click');
        aLink.dispatchEvent(event);
    }
    
    var data = '"Column One","Column Two","Column Three"';
    downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data));
    

提交回复
热议问题