HTML5教程

HTML Table转Excel表格(tableToExcel)

本文主要是介绍HTML Table转Excel表格(tableToExcel),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

原代码来自:https://www.cnblogs.com/thetree/p/13596676.html

 

我将tableToExcel函数改为两参数,分别是 表格的选择器 和 自定义文件名

<script>
    function base64(content) {
        return window.btoa(unescape(encodeURIComponent(content)));
    }
    function tableToExcel(tableSelector, fileName) {
        var excelContent = $(''+tableSelector).html();
        var excelFile = "<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'>";
        excelFile += "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>";
        excelFile += "<body><table width='10%'  border='1'>";
        excelFile += excelContent;
        excelFile += "</table></body>";
        excelFile += "</html>";
        var link = "data:application/vnd.ms-excel;base64," + base64(excelFile);
        var a = document.createElement("a");
        a.download = fileName + ".xlsx";
        a.href = link;
        a.click();
    }
</script>

 

 例如table的class="form-table",自定义文件名为“infomation”

调用时就可以写为 tableToExcel(".form-table" , "infomation");

弹出下载框,其中文件名是infomation.xlsx

 

这篇关于HTML Table转Excel表格(tableToExcel)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!