Convert JavaScript variable value to csv file

后端 未结 2 917
猫巷女王i
猫巷女王i 2020-12-03 03:42

I have a comma separated variable in my .js file, for example:

var out=\'\';
out+=\"1,val1,val2,val3,val4\\n\";
out+=\"2,val1,val2,val3,val4\\n\";
out+=\"3,v         


        
相关标签:
2条回答
  • 2020-12-03 03:57

    Depends on browser support, but that's getting pretty good with new browsers: http://jsfiddle.net/3fMeL/2/

    var CSV = [
        '"1","val1","val2","val3","val4"',
        '"2","val1","val2","val3","val4"',
        '"3","val1","val2","val3","val4"'
      ].join('\n');
    
    window.URL = window.webkitURL || window.URL;
    
    var contentType = 'text/csv';
    
    var csvFile = new Blob([CSV], {type: contentType});
    
    var a = document.createElement('a');
    a.download = 'my.csv';
    a.href = window.URL.createObjectURL(csvFile);
    a.textContent = 'Download CSV';
    
    a.dataset.downloadurl = [contentType, a.download, a.href].join(':');
    
    document.body.appendChild(a);
    

    So the first item is the Blob object, this creates the object that can be downloaded. https://developer.mozilla.org/en-US/docs/Web/API/Blob (http://caniuse.com/#search=blob)

    The next part is the download attribute of the link, which informs the browser to download the CSV file rather than opening it in the browser window. (http://caniuse.com/#feat=download)

    0 讨论(0)
  • 2020-12-03 04:00

    there is jquery plugin for output file at the client side without server side interaction,

    https://github.com/dcneiner/Downloadify

    0 讨论(0)
提交回复
热议问题