Search code examples
javascriptvelo

Is there a way to create a file from csv data and download it


On wix i have a form that uploads a bunch of info to a database (name, email, address, etc.). I then have a separate page that takes the data from the database and compiles it into a CSV format.

It currently outputs this into a textbox which from there i can copy into a txt file and change the extention to csv. This works perfectly fine for me, but im not positive if others will be able to do the same.

So, my question is whether or not there is a way to convert that data into a file then download it?

my data looks something like this:

"_id, lastName, firstName

345893458, Smith, John"


Solution

  • I figured it out, for anyone wondering here's the solution.

    You need to create an iframe object on your wix page

    then you change its html code to read something like:

    <!doctype html>
    <html>
    <head>
    
    <script type="text/javascript">
      function init () {
        window.onmessage = (event) => {
          if (event.data) {
            download('data.csv', event.data)
          }
        }
      }
    
      //download file
      function download(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' +                     encodeURIComponent(text));
        element.setAttribute('download', filename);
    
        element.style.display = 'none';
        document.body.appendChild(element);
    
        element.click();
    
        document.body.removeChild(element);
      }
    
      </script>
    
    </head>
      <body onload="init();" style="background-color:black;">
      </body>
    </html>
    

    note setting the background color is important, not exactly sure why but im pretty sure it initializes the code somehow.

    Next you want to add a line like this into your wix code editor

    export function button2_click(event) {
      // send message to the HTML Component
      let data = $w('#output').value
      $w("#html1").postMessage(data);
    }
    

    with 'output' being the id of the text box containing csv data (you can get data from somewhere else) and 'html1 being the id of the iframe container

    make sure the function is linked to a button push.