How to Export a HTML Table to Excel using Javascript

Sathish Nadarajan
 
Solution Architect
August 16, 2015
 
Rate this article
 
Views
41473

In the recent SharePoint development changes, I noticed that, most of the customers are moving towards the Client side development. Especially the CSOM and the JSOM. In the same manner, I met with an interesting requirement like, I need to export a HTML table like structure to Export using the Javascript. As I mentioned earlier, nobody wants C# to be written nowadays.

So let us see, how it is going to be.

I have a button like this.

 <button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>

On Click of that button, let me call a method called fnExcelReport().

 function fnExcelReport()
         {
               var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
               var textRange; var j=0;
               tab = document.getElementById('{818AAD80-3CAD-48C6-AABA-D0A225A4D08F}-{70352EC0-82B2-4175-98A2-84A9B95003BA}'); // id of table
 
               for(j = 0 ; j < tab.rows.length ; j++) 
               {     
                     tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
                     //tab_text=tab_text+"</tr>";
               }
 
               tab_text=tab_text+"</table>";
  
 
               var ua = window.navigator.userAgent;
               var msie = ua.indexOf("MSIE "); 
 
               if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv:11./))      // If Internet Explorer
               {
                  txtArea1.document.open("txt/html","replace");
                  txtArea1.document.write(tab_text);
                  txtArea1.document.close();
                  txtArea1.focus(); 
                  sa=txtArea1.document.execCommand("SaveAs",true,"Global View Task.xls");
               }  
               else //other browser not tested on IE 11
                  sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  
                 return (sa);
         }
 

Before that, I need to keep a hidden Iframe anywhere on the document. This requires only for the Internet Explorer. The other browsers don’t require this. Because, the lengthy content cannot be rendered in the IE.

The hidden Iframe is like

 <iframe id="txtArea1" style="display:none"></iframe>

 

Happy Coding,

Sathish Nadarajan.

Category : JavaScript, SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment