Exporting A Generated HTML Table As Excel With Rails, Turbolinks, Jquery And...

I needed a way to just quickly export a freshly created table into an Excel file for the customer, should they want it. Easy Peasy, thanks to Google!
Now here’s a disclaimer, I didn’t write much of this. I just copied it from a few different sources and mashed it into something that worked for me! So here goes;

What You Need
  • You need that nice looking HTML table of yours, probably all dynamically generated and what-not, plopped into an excel file!
  • What You Have
  • That nice looking HTML table!
  • And some gumption!
How We're Going To Do It
First up we need your table with a unique ID;
<table id="route-table" class="table table-striped table-bordered table-condensed">
  <tbody> 
    <tr>
   …
Then we’re going to need to create a new export.js file in your assets folder;
function exportTableToExcel(tableID, filename = ''){
 var downloadLink;
 var dataType = 'application/vnd.ms-excel';
 var tableSelect = document.getElementById(tableID);
 var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
 
 // Specify file name
 filename = $('#query_route option:selected').text()+'.xlsx';
 
 // Create download link element
 downloadLink = document.createElement("a");
 
 // document.body.appendChild(downloadLink);
 $('.download').append(downloadLink);
 
 if(navigator.msSaveOrOpenBlob){
 var blob = new Blob(['\ufeff', tableHTML], {
 type: dataType
  });
 navigator.msSaveOrOpenBlob( blob, filename);
 }else{
 // Create a link to the file
 downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
 
 // Setting the file name
 downloadLink.download = filename;
 
 //triggering the function
 downloadLink.click();
 }
 }
Now I know there’s a lot there, but trust me… Just ignore it. The only important one is the filename variable. That just has to be something in your page, or something hard-coded, or something generic, or literally anything other than my Jquery selector. K? k. But make sure you add on the file extension for an Excel file like I’ve got. K? k.
Lastly we are going to need a button. Just a standard button. That calls that function from the JS file. See below;
<button id="js-export-excel" onclick="exportTableToExcel('route-table')">Export Table Data To Excel File</button>
What a basic ass button. It just calls the function, passes in the table ID , and that’s about it. What a life.

You should now have a downloaded Excel sheet with all the data and none of the formatting! Hurray!

Comments (Coming Soon)