2013-07-10 20 views
10

Ciao Sto cercando di esportare un file come file .csv, in modo che quando l'utente fa clic sul pulsante di download, il browser scarica automaticamente il file come .csv. voglio anche essere in grado di impostare un nome per il file .csv da esportareUtilizzo di javascript per scaricare il file come file.csv

Sto usando javascript per fare questo codice

è qui sotto:

function ConvertToCSV(objArray) { 
      var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; 
      var str = ''; 

      for (var i = 0; i < array.length; i++) { 
       var line = ''; 
      for (var index in array[i]) { 
       if (line != '') line += ',' 

       line += array[i][index]; 
      } 

      str += line + '\r\n'; 
     } 

     return str; 
    } 

    // Example 
    $(document).ready(function() { 

     // Create Object 
     var items = [ 
       { "name": "Item 1", "color": "Green", "size": "X-Large" }, 
       { "name": "Item 2", "color": "Green", "size": "X-Large" }, 
       { "name": "Item 3", "color": "Green", "size": "X-Large" }]; 

     // Convert Object to JSON 
     var jsonObject = JSON.stringify(items); 

     // Display JSON 
     $('#json').text(jsonObject); 

     // Convert JSON to CSV & Display CSV 
     $('#csv').text(ConvertToCSV(jsonObject)); 

     $("#download").click(function() { 
      alert("2"); 
      var csv = ConvertToCSV(jsonObject); 
      window.open("data:text/csv;charset=utf-8," + escape(csv)) 
      /////// 


     }); 

    }); 

Si prega di avvisare su questo il mio capo è fiato sul collo su questo tema

Aiutaci

+0

ti è capitato di farlo funzionare? –

risposta

11

nei browser moderni c'è un nuovo att ributa in ancore.

download

http://caniuse.com/download

così invece di utilizzare

window.open("data:text/csv;charset=utf-8," + escape(csv)) 

creare un link per il download:

<a href="data:text/csv;charset=utf-8,'+escape(csv)+'" download="filename.csv">download</a> 

un'altra soluzione è quella di utilizzare php

EDIT

io non uso jQuery, ma è necessario modificare il codice per aggiungere il link per il download con qualcosa di simile nella funzione.

var csv=ConvertToCSV(jsonObject), 
a=document.createElement('a'); 
a.textContent='download'; 
a.download="myFileName.csv"; 
a.href='data:text/csv;charset=utf-8,'+escape(csv); 
document.body.appendChild(a); 
+0

Ciao, ma non riesco a scaricare il contenuto. Voglio che ci siano più codici da modificare –

+0

cosa intendi? utilizzare onefo i browser di supporto (chrome per esempio). Con javascript inserire dinamicamente i dati href e il nome del file di download. – cocco

+0

'+ escape (csv) +' questo è ciò che vedo nel file excel –

17

ho scritto una soluzione in questa discussione: how to set a file name using window.open

Questa è la soluzione più semplice:

$("#download_1").click(function() { 
var json_pre = '[{"Id":1,"UserName":"Sam Smith"},{"Id":2,"UserName":"Fred Frankly"},{"Id":1,"UserName":"Zachary Zupers"}]'; 
var json = $.parseJSON(json_pre); 

var csv = JSON2CSV(json); 
var downloadLink = document.createElement("a"); 
var blob = new Blob(["\ufeff", csv]); 
var url = URL.createObjectURL(blob); 
downloadLink.href = url; 
downloadLink.download = "data.csv"; 

document.body.appendChild(downloadLink); 
downloadLink.click(); 
document.body.removeChild(downloadLink); 
}); 

funzione JSON2CSV

function JSON2CSV(objArray) { 
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; 
    var str = ''; 
    var line = ''; 

    if ($("#labels").is(':checked')) { 
     var head = array[0]; 
     if ($("#quote").is(':checked')) { 
      for (var index in array[0]) { 
       var value = index + ""; 
       line += '"' + value.replace(/"/g, '""') + '",'; 
      } 
     } else { 
      for (var index in array[0]) { 
       line += index + ','; 
      } 
     } 

     line = line.slice(0, -1); 
     str += line + '\r\n'; 
    } 

    for (var i = 0; i < array.length; i++) { 
     var line = ''; 

     if ($("#quote").is(':checked')) { 
      for (var index in array[i]) { 
       var value = array[i][index] + ""; 
       line += '"' + value.replace(/"/g, '""') + '",'; 
      } 
     } else { 
      for (var index in array[i]) { 
       line += array[i][index] + ','; 
      } 
     } 

     line = line.slice(0, -1); 
     str += line + '\r\n'; 
    } 
    return str; 
} 
+0

dove si ottiene JSON2CSV (json) che librerie da –

+0

@ pato.llaguno Controlla il mio codice aggiornato – Jewel

+0

Controlla il thread seguente: http://stackoverflow.com/a/24643984/1079270 – Jewel

0

Volevo solo aggiungere del codice qui per le persone in futuro poiché stavo cercando di esportare JSON in un documento CSV e downlo ad esso.

Io uso $.getJSON per estrarre dati json da una pagina esterna, ma se si dispone di un array di base, è sufficiente utilizzarlo.

Questo utilizza il codice Christian Landgren's per creare i dati csv.

$(document).ready(function() { 
    var JSONData = $.getJSON("GetJsonData.php", function(data) { 
     var items = data; 
     const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here 
     const header = Object.keys(items[0]); 
     let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(',')); 
     csv.unshift(header.join(',')); 
     csv = csv.join('\r\n'); 

     //Download the file as CSV 
     var downloadLink = document.createElement("a"); 
     var blob = new Blob(["\ufeff", csv]); 
     var url = URL.createObjectURL(blob); 
     downloadLink.href = url; 
     downloadLink.download = "DataDump.csv"; //Name the file here 
     document.body.appendChild(downloadLink); 
     downloadLink.click(); 
     document.body.removeChild(downloadLink); 
    }); 
}); 
Problemi correlati