美文网首页
javascript 把页面表格下载成excel

javascript 把页面表格下载成excel

作者: luke_skywalker | 来源:发表于2018-08-22 09:19 被阅读0次
// 把页面的表格转化为excel下载下来
function tablesToExcel(table, name, filename) {

    var uri = "data:application/vnd.ms-excel;base64,"
        ,
        template = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>"
        , templateend = "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>"
        , body = "<body>"
        , tablevar = "<table>{table"
        , tablevarend = "}</table>"
        , bodyend = "</body></html>"
        , worksheet = "<x:ExcelWorksheet><x:Name>"
        , worksheetend = "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
        , worksheetvar = "{worksheet"
        , worksheetvarend = "}"
        , base64 = function (s) {
            return window.btoa(unescape(encodeURIComponent(s)));
        }
        , format = function (s, c) {
            return s.replace(/{(\w+)}/g, function (m, p) {
                return c[p];
            });
        }
        , wstemplate = ""
        , tabletemplate = "";

    var tables = table;

    for (var i = 0; i < tables.length; ++i) {
        wstemplate += worksheet + worksheetvar + i + worksheetvarend + worksheetend;
        /*
         *  addd <td></td> let two table arrange left and right
         */
        if (tables.length > 1) {
            tabletemplate += "<td>" + tablevar + i + tablevarend + "</td>";
        } else {
            tabletemplate += tablevar + i + tablevarend;
        }
    }

    /*
     * add <table><tr> and </table></tr> to Conbime left_tab and right_tab to one table
     */
    if (tables.length > 1) {
        tabletemplate = "<table><tr>" + tabletemplate + "</table></tr>";
    }

    var allTemplate = template + wstemplate + templateend;
    var allWorksheet = body + tabletemplate + bodyend;
    var allOfIt = allTemplate + allWorksheet;

    var ctx = {};
    for (var j = 0; j < tables.length; ++j) {
        ctx["worksheet" + j] = name[j];
    }

    for (var k = 0; k < tables.length; ++k) {
        var exceltable;
        if (!tables[k].nodeType) exceltable = document.getElementById(tables[k]);
        ctx["table" + k] = exceltable.innerHTML;
    }

    window.location.href = uri + base64(format(allOfIt, ctx));
}

相关文章

网友评论

      本文标题:javascript 把页面表格下载成excel

      本文链接:https://www.haomeiwen.com/subject/msleiftx.html