Free programming examples and instructions

Export HTML table to excel - Javascript

Demo and code for how to export HTML table o excel in Javascript.

by Athil

Posted on 27 Jun 2018 Category: Javascript Views: 3263

Here I am going to show how to export HTML table to excel using javascript.


HTML Table   

<h2 id="caption"> Students Report  </h2>

    <table id="tblstudentsreport"> 

            <td> Name1</td>
            <td> [email protected]</td>
            <td> 1234567890 </td>
            <td> Name2</td>
            <td> [email protected]</td>
            <td> 2345678901 </td>
            <td> Name3</td>
            <td> [email protected]</td>
            <td> 3456789012 </td>


            var tab_text = "<table border='2px'><tr><td colspan='3'><center><b>" + document.getElementById('caption').innerText + "</b></center></td></tr> <tr bgcolor='#87AFC6'>";
            var textRange; var j = 0;
            tab = document.getElementById('tblstudentsreport'); // id of table

            for (j = 0 ; j < tab.rows.length ; j++) {
                tab_text = tab_text + tab.rows[j].innerHTML + "</tr>";

            tab_text = tab_text + "</table>";
            tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
            tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
            tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

            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");

                sa = txtArea1.document.execCommand("SaveAs", true, ".xls");

            else                 //other browser not tested on IE 11
                sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
            return (sa);


Leave a Comment:

Click here to register

Popular articles