在系統開發中,經常會遇到要將一個表格資料匯出到excel中,剛剛做完,把示例程式碼共享一下,話不多說直接上程式碼。

<!DOCTYPE html>  
<html>  
<head lang="en">  
    <meta charset="UTF-8">  
    <title>html 表格匯出道</title>  
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
   
</head>  
<body>  
  
<div >  
    
</div>  
<div id="myDiv">  
<table id="tableExcel" width="100%" class="table table-hover" >  
    <tr>  
        <td colspan="5" align="center">html 表格匯出道Excel</td>  
    </tr>  
    <tr>  
        <td>列標題1</td>  
        <td>列標題2</td>  
        <td>類標題3</td>  
        <td>列標題4</td>  
        <td>列標題5</td>  
    </tr>  
    <tr>  
        <td>aaa</td>  
        <td>bbb</td>  
        <td>ccc</td>  
        <td>ddd</td>  
        <td>eee</td>  
    </tr>  
    <tr>  
        <td>AAA</td>  
        <td>BBB</td>  
        <td>CCC</td>  
        <td>DDD</td>  
        <td>EEE</td>  
    </tr>  
    <tr>  
        <td>FFF</td>  
        <td>GGG</td>  
        <td>HHH</td>  
        <td>III</td>  
        <td>JJJ</td>  
    </tr>  
</table>
<button type="button" class="btn btn-primary center-block" onclick="method5('tableExcel')">匯出Excel</button>  
<!-- <input type="file" class="btn btn-primary center-block" value="請選擇輸出路徑"> -->
<script type="text/javascript" src="js/jquery-3.1.0.js"></script>  
 <script language="JavaScript" type="text/javascript">  
        //第五種方法  
        var idTmr;  
        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';  
            }  
        }  
        function method5(tableid) {  
            if(getExplorer()=='ie')  
            {  
                var curTbl = document.getElementById(tableid);  
                var oXL = new ActiveXObject("Excel.Application");  
                var oWB = oXL.Workbooks.Add();  
                var xlsheet = oWB.Worksheets(1);  
                var sel = document.body.createTextRange();  
                sel.moveToElementText(curTbl);  
                sel.select();  
                sel.execCommand("Copy");  
                xlsheet.Paste();  
                oXL.Visible = true;  
  
                try {  
                    var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");  
                } catch (e) {  
                    print("Nested catch caught " + e);  
                } finally {  
                    oWB.SaveAs(fname);  
                    oWB.Close(savechanges = false);  
                    oXL.Quit();  
                    oXL = null;  
                    idTmr = window.setInterval("Cleanup();", 1);  
                }  
  
            }  
            else  
            {  
                tableToExcel(tableid)  
            }  
        }  
        function Cleanup() {  
            window.clearInterval(idTmr);  
            CollectGarbage();  
        }  
        var tableToExcel = (function() {  
            var uri = 'data:application/vnd.ms-excel;base64,',  
                    template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',  
                    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}  
                window.location.href = uri + base64(format(template, ctx))  
            }  
        })()  
  
    </script>  
</div>  
</body>  
</html>  

但這個示例有兩個缺陷,一是匯出的表格單元格邊框沒有樣式,二是不能自定義表格名稱,所有又進行了改進,以下是改進版本的程式碼參考。

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
</head>
<body>
	<table id="tableExcel" width="100%" class="table table-hover" >  
    <tr>  
        <td colspan="5" align="center">html 表格匯出道Excel</td>  
    </tr>  
    <tr>  
        <td>列標題1</td>  
        <td>列標題2</td>  
        <td>類標題3</td>  
        <td>列標題4</td>  
        <td>列標題5</td>  
    </tr>  
    <tr>  
        <td>aaa</td>  
        <td>bbb</td>  
        <td>ccc</td>  
        <td>ddd</td>  
        <td>eee</td>  
    </tr>  
    <tr>  
        <td>AAA</td>  
        <td>BBB</td>  
        <td>CCC</td>  
        <td>DDD</td>  
        <td>EEE</td>  
    </tr>  
    <tr>  
        <td>FFF</td>  
        <td>GGG</td>  
        <td>HHH</td>  
        <td>III</td>  
        <td>JJJ</td>  
    </tr>  
</table>
	<a id="dlink"  style="display:none;"></a>
<input type="text" name="" value="請輸入檔名" class="center-block form-control" style="margin-bottom: 20px; text-align: center" id="submit" onclick="submt()">	
<input type="button" class="btn btn-primary center-block" onclick="tableToExcel('tablename', 'name', 'zhangsan.xls')" value="Export to Excel">
</body>
<script>
	var nnn = "";
	function submt(){
		document.getElementById('submit').value="";
	}
	
	var tableToExcel = (function () {
        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><meta charset="UTF-8"><!--[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><body><table>{table}</table></body></html>'
        , 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("tableExcel")
            var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }

            document.getElementById("dlink").href = uri + base64(format(template, ctx));
            document.getElementById("dlink").download = document.getElementById('submit').value+'.xls';
            document.getElementById("dlink").click();

        }
    })()
</script>
</html>

最後感謝完成這個功能的同事微笑