Hi 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
I am using javascript to do this
Code is below:
 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))             ///////           });      });   Please advise on this My Boss is breathing down my neck on this issue
Please help
join("\n"); Then you can use JavaScript's window. open and encodeURI functions to download the CSV file like so: var encodedUri = encodeURI(csvContent); window.
Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited). Note: The different formats support different feature sets.
To ask the browser to download a file it can render, use the following header: Content-Disposition: attachment; filename="downloaded. pdf" (you can of course customize the filename as you need).
I have written a solution in this thread: how to set a file name using window.open
This is the simple solution:
 $("#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); });   JSON2CSV function
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; } 
                        in modern browsers there is a new attribute in anchors.
download
http://caniuse.com/download
so instead of using
window.open("data:text/csv;charset=utf-8," + escape(csv))   create a download link:
<a href="data:text/csv;charset=utf-8,'+escape(csv)+'" download="filename.csv">download</a>   another solution is to use php
EDIT
i don't use jQuery, but you need to edit your code to add the download link with something like that in your function.
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); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With