UncleCoder.com

UncleCoder.com

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: 153

Edited on 28 Jun 2019


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

DEMO

HTML Table   

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

    <table id="tblstudentsreport"> 
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>

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

Script

            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+"</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");
                txtArea1.document.write(tab_text);
                txtArea1.document.close();
                txtArea1.focus();


                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:


Advertisement