简体   繁体   English

使用javascript从具有复杂结构表(rowspan或colspan)的html导出Excel或csv

[英]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. 为了使此功能正常工作,在较旧的IE浏览器中,您必须拥有一个名为myFrame的 iframe ,此功能中使用了frame。 Also make sure to wrap your table inside a div , in this snippet by div's id is datatable 还要确保将表包装在div中 ,在此片段中,div的id是datatable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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