Export HTML table to Excel in JavaScript

export to excel javascript

Being UI Developer there are lot of cases where we create static HTML tables. Some times we create utilities for our vendors or website.

Why we need Excel Export

Dynamic HTML table created using JSON data, which contains useful information of any specific type. These table information can be used for future purpose.

Since data can be used for the future purpose it has to be available till then or shareable to another person in the form of the physical file via Email. To share physical file we need to export created HTML table in any file format like Excel, CSV.

JavaScript Solution

UI Developers are well verse in Client-side scripting which runs on browsers, it includes JavaScript, jQuery, AngularJS, etc. Creation of HTML table can be easily done using JavaScript, jQuery or any other frame work.

But for HTML table to Excel export, we need to work on some server-side code. Which is a totally different area of work for UI Developers.

Implementation

But here come with a solution for excel export. We need to add a few lines of script codes to implement Excel Export feature.

Below are the codes we need to add for excel export feature.

JavaScript Code
function fnExcelReport(){
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>"; // bgcolor will give color to your first row
    var textRange; var j=0;
    tab = document.getElementById('headerTable'); // 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,"Say Thanks to Submit.xls");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

Apart from JavaScript function add headerTable id to your HTML table you want to export. after add ID your table tag will be like below

<table class="tablegst" id="headerTable">

Now we need button tag to execute our JavaScript function.

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

You are done with your excel export feature. Try to your HTML demo.

See it in action