Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Download CSV as File

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

<script>
var data = '"Column One","Column Two","Column Three"';
window.location.href = 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data);
</script>

So far this is working, but as the browser prompts me to save the file, there is no filename, nor extension.

How can I predetermine the name of the file and it's extension, inside the window.location.href ?

like image 689
coffeemonitor Avatar asked Jan 17 '14 03:01

coffeemonitor


People also ask

How do I save a CSV file in JavaScript?

Click on the given Export to HTML table to CSV File button to download the data to CSV file format. The file will download by the name of person.

How do I download as a CSV file?

Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited). Note: The different formats support different feature sets.


3 Answers

function downloadFile(fileName, urlData) {

    var aLink = document.createElement('a');
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("click");
    aLink.download = fileName;
    aLink.href = urlData;
    aLink.dispatchEvent(evt);
}

var data = '"Column One","Column Two","Column Three"';
downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data));

http://jsfiddle.net/rooseve/7bUG8/

like image 103
Andrew Avatar answered Oct 16 '22 22:10

Andrew


In my case, it turned out that Excel ignored the charset=UTF-8 part. I found a solution in this post, to force Excel to take into account the UTF-8. So this last line did the trick for me:

downloadFile('2.csv', 'data:text/csv;charset=UTF-8,' + '\uFEFF' + encodeURIComponent(data));
like image 29
user1826063 Avatar answered Oct 16 '22 23:10

user1826063


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));
like image 9
Jeff Sallans Avatar answered Oct 16 '22 23:10

Jeff Sallans