简体   繁体   中英

Export excel or csv from html with complex structure table (rowspan or colspan) using javascript

I am working on angular project. Now i need to export data to excel in complex table structure. Are there any libraries that can handle this for me? 在此处输入图片说明

You can try below function :

function ExportToExcel(fileName)
{
    var isIE = (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0); 
    if (isIE) {
        // IE > 10
        if (typeof Blob != 'undefined') {
            var fileData = new Blob([document.getElementById("datatable").innerHTML.replace(/="  "/gi, "")], {type: 'application/vnd.ms-excel,'});
            window.navigator.msSaveBlob(fileData, fileName + '.xls');
        }
        // IE < 10
        else {
            myFrame.document.open("text/html", "replace");
            myFrame.document.write(document.getElementById("datatable").innerHTML.replace(/="  "/gi, ""));
            myFrame.document.close();
            myFrame.focus();
            myFrame.document.execCommand('SaveAs', true, fileName + '.xls');
        }

    }
    // crome,mozilla
    else {
    var uri = 'data:application/vnd.ms-excel,' + document.getElementById("datatable").innerHTML.replace(/ /g, '%20');
        var link = document.createElement("a");
        link.href = uri;
        link.style = "visibility:hidden";
        link.download = fileName + ".xls";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

In order to make this function work, in older IE browser you are required to have and iframe with name myFrame , this is frame is used in this function. Also make sure to wrap your table inside a div , in this snippet by div's id is datatable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM