Export CSV data via JS

Asked

Viewed 979 times

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 have never done this type of event in J. Someone can help me?

1 answer

0


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

The 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 PHP page 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 must create a button on the page with the name "Download file" which will call the above function:

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

Or you can create a link:

<a href="javascript:void(0)" onclick="baixar()">Baixar arquivo</a>
  • Fantastic... Thank you so much!!

  • @Marcusbotelho Valeu! Consider scoring in the answer if you found it useful. Abs!

  • It did. Again, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.