If anyone has been following my blog or twitter or talking to me you will know that a good deal of my day is spent in Visual Studio. I have a few different projects happening at any given time and since I’m not a developer it can take me a bit of time to get stuff done. So a work project of mine has been updating our customer facing portal to rely less on server side processing and move it all to client-side. This has lots of advantages but not in the least is to create a better experience for customers.
When we made this move, I started moving lots of large server-side processes to client side Web API 2 calls. And with the move away from server-side I really wanted to retain some features that are easy to do in a server-side. One of those is exporting data to CSV. This is so simple on the server-side its crazy. But on the client side it takes a bunch of work to make it happen.
Since I’m not a JavaScript expert I started by hunting around and I found someone who built a good part of this. (CREDIT: Danny Pule)
This got me three-quarters of the way there but I wanted to be able to consume the Web API. All of the examples I had found were with defined data and I of course was going to be getting a JSON result. So after a bit more research I found a way to take elements from Danny’s work, make it usable for myself and create a robust framework for my needs.
So what you need to update are:
- Lines 53 to 55 with your CSV Header Names
- Lines 58 with your Web API 2 Location
- Lines 70 to 74 with your Header Information. You need to make sure that these values match what is being returned from your Web/JSON return.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | </script> 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; } function exportCSVFile(headers, items, fileTitle) { if (headers) { items.unshift(headers); } // Convert Object to JSON var jsonObject = JSON.stringify(items); var csv = this.convertToCSV(jsonObject); var exportedFilenmae = fileTitle + '.csv' || 'export.csv'; var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, exportedFilenmae); } else { var link = document.createElement("a"); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute var url = URL.createObjectURL(blob); link.setAttribute("href", url); link.setAttribute("download", exportedFilenmae); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } } function download() { var headers = { CustomerName: "Customer", InvoiceEmail: "Invoice Address", TechnicalEmail: "Technical Address" }; let url = 'https://api.domain.com/GetContacts/{variable}/{variable}'; fetch(url) .then(res => res.json()) .then((out) => { var itemsNotFormatted = []; itemsNotFormatted = out; var itemsFormatted = []; // format the data itemsNotFormatted.forEach((item) => { itemsFormatted.push({ Name1: item.Value1, Name2: item.Value2, Name3: item.Value3 }); }); var fileTitle = 'AdditionalCompanyContacts'; exportCSVFile(headers, itemsFormatted, fileTitle); }) .catch(err => { throw err }); } </script> <style type="text/css"> .download-wrapper { cursor: pointer; &:hover { opacity: .7; } } </style> |
Then all you need to do is add a DIV that calls the download() function:
1 2 3 | <div style="float: right;" class="download-wrapper" onClick="download()"> <i class="fa fa-download fa-lg"></i> Export Data (CSV) </div> |
Again, the thanks to Danny Pule for the first part about how to client-side export. Make sure to check out Danny’s blog for all sort of cool code tips.