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
?
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.
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.
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/
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));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With