Export CSV data via JS

2

I have a data set in the database in my back end , and I need to create a button on which the user will click to export this data in CSV format. But I've never done this kind of event in JS. Can anyone help me?

    
asked by anonymous 14.12.2017 / 21:44

1 answer

0

You can create an Ajax by returning a comma-separated list of data from a PHP page (or another back-end script), and the user can download the file .csv :

JavaScript is this:

function baixar(){

   link_ = document.querySelector("#downloadcsv");

   if(link_){
      link_.outerHTML = '';
   }

   var http = false;
   http = new XMLHttpRequest();

   var url_="retorno.php";
   http.open("GET",url_,true);
   http.onreadystatechange=function(){
      if(http.readyState==4){
         var forma = "data:text/csv;charset=utf-8,";
         forma += http.responseText;

         // se quiser os valores separados por ; (ponto e vírgula)
         // substitua a linha acima por:
         // forma += http.responseText.split(",").join(";");

         var encoda = encodeURI(forma);
         var baixa = document.createElement("a");
         baixa.setAttribute("href", encoda);
         baixa.setAttribute("id", "downloadcsv");
         baixa.setAttribute("download", "arquivo.csv");
         document.body.appendChild(baixa);
         baixa.click();
      }
   }
   http.send(null);

}

Where retorno.php is the page in PHP that will return the database data. The returned data should come in the format below:

dado1,dado2,dado3

And arquivo.csv is the name of the file that will be downloaded.

You should create a button on the page named "Download File" which will call the function above:

<input type="button" value="Baixar arquivo" onclick="baixar()">

Or you can create a link:

<a href="javascript:void(0)" onclick="baixar()">Baixar arquivo</a>
    
14.12.2017 / 23:09