Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 985
Palak Avatar asked Feb 23 '17 15:02

Palak


People also ask

How do I Export a table from HTML to Excel?

To convert HTML table data into excel, we need to use the SheetJS library. Using SheetJs we can easily convert our table data into an Xls file. We can download the js file from Github or directly use the CDN hosted file. We are done with HTML markup and import Sheetjs library.


1 Answers

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.

like image 101
Ishara Fernando Avatar answered Oct 30 '22 13:10

Ishara Fernando