Is there a way to create a CSV file using pure JavaScript (offline, locally) and downloading that file to the local file system? The approach should work in IE9 or lower.
I have tried downloadify, but cross-domain issues prevented me from using it locally. I also tried creating a Base64 encoded string and issuing a text/csv data URI, but IE doesn't appear to support data URIs for that particular case.
If you want to open the csv in excel 2013 with correct utf8, you should add utf8 bom to dinesh ygv code like this:
<a id="export" class="myButton" download="" href="#">export</a>
<script>
function createDownloadLink(anchorSelector, str, fileName){
if(window.navigator.msSaveOrOpenBlob) {
var fileData = ['\ufeff'+str];
blobObject = new Blob(fileData);
$(anchorSelector).click(function(){
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
});
} else {
var url = "data:text/plain;charset=utf-8,%EF%BB%BF" + encodeURIComponent(str);
$(anchorSelector).attr("download", fileName);
$(anchorSelector).attr("href", url);
}
}
$(function () {
var str = "hi,file";
createDownloadLink("#export",str,"file.txt");
});
</script>
The following method works in IE11+, Firefox 25+ and Chrome 30+:
<a id="export" class="myButton" download="" href="#">export</a>
<script>
function createDownloadLink(anchorSelector, str, fileName){
if(window.navigator.msSaveOrOpenBlob) {
var fileData = [str];
blobObject = new Blob(fileData);
$(anchorSelector).click(function(){
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
});
} else {
var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
$(anchorSelector).attr("download", fileName);
$(anchorSelector).attr("href", url);
}
}
$(function () {
var str = "hi,file";
createDownloadLink("#export",str,"file.txt");
});
</script>
See this in action: JS Fiddle
Firefox and Chrome support data URI for navigation, which allows us to create files by navigating to a data URI, while IE doesn't support it for security purposes.
On the other hand, IE has API for saving a blob, which can be used to create and download files.
For security reasons, no, it's not possible to create a file locally and save it to the user's file system. JavaScript simply doesn't allow it. The file will need to be created server side and the user will need to download it.
Edit: Actually, you can access the local file system using HTML5, but it appears IE9 doesn't support the File API.
You can use the data
links for non-IE browsers, then fall back to an IFrame
with document.execCommand
for Internet Explorer.
I have more details here:
https://stackoverflow.com/a/26003382/378151
I've tested it on IE9-IE11. I don't know what the compatibility is below that, and it seems like no one else really knows either. If I were to guess, I'd wager that IE 8 supports this and IE 6 & 7 is where it gets flaky.