html页面表格转Excel

//tableid:表格id 创建一个a标签,id为download
//jQuery HTML导出Excel文件(兼容IE及所有浏览器)    
    function HtmlExportToExcel(tableid) {
        var filename = "下载的Excel名称";
        if (getExplorer() == 'ie' || getExplorer() == undefined) {
            HtmlExportToExcelForIE(tableid, filename);
        }
        else {
            HtmlExportToExcelForEntire(tableid, filename)
        }
    }
    //IE浏览器导出Excel
    function HtmlExportToExcelForIE(tableid, filename) {
        try {
            var winname = window.open('', '_blank', 'top=10000');
            var strHTML = document.getElementById(tableid).innerHTML;

            winname.document.open('application/vnd.ms-excel', 'export excel');
            winname.document.writeln(strHTML);
            winname.document.execCommand('saveas', '', filename + '.xls');
            winname.close();

        } catch (e) {
            alert(e.description);
        }
    }
    //非IE浏览器导出Excel
    var HtmlExportToExcelForEntire = (function() {
        var uri = 'data:application/vnd.ms-excel;base64,',
            template = '{table}
', base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) { table = document.getElementById(table); } var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML } document.getElementById("download").href = uri + base64(format(template, ctx)); document.getElementById("download").download = name + ".xls"; document.getElementById("download").click(); } })() function getExplorer() { var explorer = window.navigator.userAgent; //ie if (explorer.indexOf("MSIE") >= 0) { return 'ie'; } //firefox else if (explorer.indexOf("Firefox") >= 0) { return 'Firefox'; } //Chrome else if (explorer.indexOf("Chrome") >= 0) { return 'Chrome'; } //Opera else if (explorer.indexOf("Opera") >= 0) { return 'Opera'; } //Safari else if (explorer.indexOf("Safari") >= 0) { return 'Safari'; } }

 

你可能感兴趣的:(html页面表格转Excel)