title: Using javascript to download file as a.csv file
body: <p>I am trying to export a file as .csv file so that when the user clicks on the download button, the browser would automatically download the file as .csv.
  I also want to be able to set a name for the .csv file to be exported</p>
  <p>I am using javascript to do this</p>
  <p>The code is below:</p>
  <pre><code>function ConvertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';
  
    for (var i = 0; i &lt; 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 = [
      { &quot;name&quot;: &quot;Item 1&quot;, &quot;color&quot;: &quot;Green&quot;, &quot;size&quot;: &quot;X-Large&quot; },
      { &quot;name&quot;: &quot;Item 2&quot;, &quot;color&quot;: &quot;Green&quot;, &quot;size&quot;: &quot;X-Large&quot; },
      { &quot;name&quot;: &quot;Item 3&quot;, &quot;color&quot;: &quot;Green&quot;, &quot;size&quot;: &quot;X-Large&quot; }];
  
    // Convert Object to JSON
    var jsonObject = JSON.stringify(items);
  
    // Display JSON
    $('#json').text(jsonObject);
  
    // Convert JSON to CSV &amp; Display CSV
    $('#csv').text(ConvertToCSV(jsonObject));
  
    $(&quot;#download&quot;).click(function() {
      alert(&quot;2&quot;);
      var csv = ConvertToCSV(jsonObject);
      window.open(&quot;data:text/csv;charset=utf-8,&quot; + escape(csv))
      ///////
  
    });
  
  });
  </code></pre>