How to Export a HTML Table to Excel using Javascript

Sathish Nadarajan
SharePoint MVP
Published On :   16 Aug 2015
Visit Count
Today :  11    Total :   32908

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++) 
               var ua = window.navigator.userAgent;
               var msie = ua.indexOf("MSIE "); 
               if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
                  sa=txtArea1.document.execCommand("SaveAs",true,"Global View Task.xls");
               else //other browser not tested on IE 11
                  sa ='data:application/,' + 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.