Download Excel file in xlsx format using Javascript (exporting html tables into Excel)

11,019

This is because content is not of type "xls". i.e. if excel is of type "xlsx" you will get this error. Try with other excel extensions with file name.

Share:
11,019
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am using JS, HTML and CSS to build my application and host it on a server. I am using the following code to import all the html tables to an excel file in xls format.

    function fnExcelReport(tableNames) {
        var tab_text = "";
        var arrTableNames = tableNames.split("|");
        if (arrTableNames.length > 0) {
            for (var i = 0; i < arrTableNames.length; i++) {
    
                    tab_text = tab_text + "<table border='1px'>";
    
                tab = document.getElementById(arrTableNames[i]); 
    
    
                for (j = 0; j < tab.children.length; j++) {
                    tab_text = tab_text + tab.children[j].innerHTML;
                }
                tab_text = tab_text + "</table><br/><br/>";
                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
        {
            if (window.navigator.msSaveBlob) {
                var blob = new Blob([tab_text], {
                    type: "data:application/vnd.ms-excel;"
                });
                sa = navigator.msSaveBlob(blob, "report.xls");
            }
        } else //other browser not tested on IE 11
            sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
    
        return (sa);
    }
    

    I am able to download the file and open it, but I get the following warning message when I open it:

    Warning message on Excel image

    When I click yes, all my data is displayed correctly on the Excel file. I don't want to see that warning message. How do I change my code such that it opens with an xlsx format and removes the warning message?