html table表格匯出excel的方法
阿新 • • 發佈:2019-02-02
先上程式碼
<script type="text/javascript" language="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 method1(tableid,name="1.xlsx") { //整個表格拷貝到EXCEL中 if (getExplorer() == 'ie') { var curTbl = document.getElementById(tableid); var oXL = new ActiveXObject("Excel.Application"); //建立AX物件excel var oWB = oXL.Workbooks.Add(); //獲取workbook物件 var xlsheet = oWB.Worksheets(1); //啟用當前sheet var sel = document.body.createTextRange(); sel.moveToElementText(curTbl); //把表格中的內容移到TextRange中 sel.select; //全選TextRange中內容 sel.execCommand("Copy"); //複製TextRange中內容 xlsheet.Paste(); //貼上到活動的EXCEL中 oXL.Visible = true; //設定excel可見屬性 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); //xls.visible = false; oXL.Quit(); oXL = null; //結束excel程序,退出完成 //window.setInterval("Cleanup();",1); idTmr = window.setInterval("Cleanup();", 1); } } else { tableToExcel(tableid,name) } } function Cleanup() { window.clearInterval(idTmr); CollectGarbage(); } 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><!--[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) { console.log(table,name) if (!table.nodeType) table = document.getElementById(table) var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML } return; window.location.href = uri + base64(format(template, ctx)) } })(); </script>
$('#export').click(function () {
method1('table');
})
$('#export').attr('href',uri + base64(format(template, ctx))) //解決檔案無副檔名的問題
轉載自http://blog.csdn.net/sinat_15114467/article/details/51098522
github也有寫好的外掛:
jQuery table2excel - v1.1.1 * jQuery plugin to export an .xls file in browser from an HTML table * https://github.com/rainabba/jquery-table2excel
這個地址也是相關的介紹https://segmentfault.com/a/1190000000336643
我的html例項
<!DOCTYPE html> <html lang="en"> <head> <meta charset="gb2312"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>資料</title> <style> * { margin: 0; padding: 0; text-decoration: none; list-style: none; font-size: 20px; } body{ text-align: center; } .agent{ text-align: left; } table { width: 1200px; margin: 0 auto; vertical-align: center; font-size: 18px; text-align: center; border: 1px solid #ccc; } td, th { border: 1px solid #000; overflow: hidden; } .kefu { width: 70px; } .page { text-align: center; font-size: 20px; } .page a { display: inline-block; } #export { display: block; text-align: center; font-size: 20px; } /* 時間和日期 */ #choose { width: 1200px; margin: 20px auto; text-align: center; } /* 對話方塊 */ .convBox { position: fixed; top: 0px; left: 0; bottom: 0; right: 0; margin: auto; width: 1200px; height: 500px; overflow: auto; display: none; background: #ccc; border: 1px solid #000; } .convBox h6 { font-size: 20px; margin: 15px 0; text-align: center; } .convBox .close { position: absolute; top: 8px; right: 8px; font-size: 20px; } .convBox li { float: left; margin: 8px 20px; } .clearfix:after { content: ''; display: block; height: 0; visibility: hidden; clear: both; } .clearfix { zoom: 1; } .mainCon .agent, .mainCon .client { padding: 8px 20px; } .mainCon .client { text-align: right; background: #68c558; } </style> </head> <body> <div id="choose"> <input type="text" class="startTm"> <input type="text" class="endTm"> <button>提交</button> </div> <table id="table"> <tr> <th>編號</th> <th>對話開始時間</th> <th>會話結束時間</th> <th>客戶id</th> <th>搜尋關鍵詞</th> <th class="kefu">客服</th> <th>客服首次響應訪客的等待時</th> <th>訪客的訊息數</th> <th>對話內容</th> <th>客戶地點</th> <th>IP</th> </tr> </table> <p class="page"> <a href="javascript:void(0)" class="prev">上一頁</a> <a href="javascript:void(0)" class="next">下一頁</a> <span></span> </p> <a href="javascript:void(0)" id="export" download="對話記錄.xlsx">匯出對話記錄</a> <div class="convBox"> <h6><span></span>的對話</h6> <a href="javascript:void(0)" class="close">X</a> <ul class="contentKey clearfix"> <li class="agent_name"> 客服:<span>dfsdfsfs</span> </li> <li class="wait_in_secs"> 對話等待時間:<span>5</span>S </li> <li class="visitor_ip"> IP:<span>yan</span> </li> <li class="visitor_location"> 地點:<span>yan</span> </li> <li class="search_engine_kw"> 搜尋關鍵詞:<span>sdfsfsfsdfsfsfsgsdsg</span> </li> <li class="conv_start_tm"> 對話開始時間:<span>sdfsfsfsdfsfsfsgsdsg</span> </li> <li class="conv_end_tm"> 對話結束時間:<span>sdfsfsfsdfsfsfsgsdsg</span> </li> </ul> <div class="mainCon clearfix"> </div> </div> <script src="js/jquery-1.11.3.min.js"></script> <script> var tableList= '<tr>\ <th>編號</th>\ <th>對話開始時間</th>\ <th>會話結束時間</th>\ <th>客戶id</th>\ <th>搜尋關鍵詞</th>\ <th class="kefu">客服</th>\ <th>客服首次響應訪客的等待時</th>\ <th>訪客的訊息數</th>\ <th>對話內容</th>\ <th>客戶地點</th>\ <th>IP</th>\ </tr>'; $(document).ready(function () { var pageAll='';//計算總數時用的引數 var pagesize = 0; //顯示頁 var limit = 20; //每頁顯示的數目 var offset = pagesize * limit; //跳過的數目 var startTm = $('.startTm').val(); var endTm = $('.endTm').val(); //初始化時間 var startTm = getFormatDate('ymd'); var endTm = getFormatDate('ymd'); $('.startTm').val(getFormatDate('ymd')); $('.endTm').val(getFormatDate('ymd')); var data1 = { startTm: startTm, endTm: endTm, offset: 0 }; //ajax請求 function ajax(data1) { // console.log(data1) $.ajax({ url: "php/index.php", data: data1, success: function (data) { console.log(data) var newJson = JSON.parse(data); if (newJson.result.length < 20) { $('.page span').text("已經是最後一頁"); } else if (newJson.result.length <= 0) { $('.page span').text("已經是最後一頁"); return; } else { var Nowpage = pagesize + 1; $('.page span').text("當前是第" + Nowpage + "頁"); } // addContent(newJson.result) tableList+=addContent(newJson.result); $('#table').append(addContent(newJson.result)); } }) } function ajax2(data1) { $.ajax({ url: "php/index.php", data: data1, success: function (data) { var newJson = JSON.parse(data); tableList+=addContent(newJson.result); if (newJson.result.length < 20 || newJson.result.length <= 0) { // console.log(tableList) var dateN=(new Date()).toLocaleString(); // console.log(dateN) // return; method1(tableList,dateN); // return tableList; } else { allrecord(); } } }) } //調出所有的記錄 function allrecord(){ pageAll++; var offset = pageAll * limit; //跳過的數目 var startTm = $('.startTm').val(); var endTm = $('.endTm').val(); var data1 = { startTm: startTm, endTm: endTm, offset: offset } ajax2(data1); } ajax(data1); //插入對話內容 function addContent(rs) { // console.log(rs) var arr = []; var length = rs.length; for (var i = 0; i < length; i++) { if(!rs[i]){continue;} arr.push('<tr>'); arr.push('<td>' + i + '</td>'); arr.push('<td>' + rs[i].conv_start_tm + '</td>'); arr.push('<td>' + rs[i].conv_end_tm + '</td>'); arr.push('<td>' + rs[i].client_info.visitor_name + '</td>'); arr.push('<td>' + rs[i].search_engine_kw + '</td>'); arr.push('<td>' + rs[i].agent_name + '</td>'); arr.push('<td>' + rs[i].wait_in_secs + '</td>'); arr.push('<td>' + rs[i].conv_visitor_msg_count + '</td>'); if(rs[i].conv_visitor_msg_count>0){ let con = ''; let conLen = rs[i].conv_content.length; for(let j=0;j<conLen;j++){ con+=rs[i].conv_content[j].from+rs[i].conv_content[j].timestamp+rs[i].conv_content[j].content; } arr.push('<td class="convId">' + con + '<span>' + rs[i].conv_id + '</span></td>'); }else{ arr.push('<td class="convId">' + '點選顯示內容<span>' + rs[i].conv_id + '</span></td>'); } arr.push('<td>' + rs[i].visitor_location + '</td>'); arr.push('<td>'+rs[i].visitor_ip+'</td>'); arr.push('</tr>'); } // tableList+=arr.join('') // $('#table').append(arr.join('')); return arr.join(''); } $('.prev').click(function () { $("#table tr").not($("#table tr:first")).remove(); pagesize = (--pagesize < 0) ? 0 : pagesize; offset = pagesize * limit; //跳過的數目 startTm = $('.startTm').val(); endTm = $('.endTm').val(); var data1 = { startTm: startTm, endTm: endTm, offset: offset } ajax(data1); }) $('.next').click(function () { $("#table tr").not($("#table tr:first")).remove(); if ($('.page span').text() == '已經是最後一頁') { return false; } pagesize = (++pagesize < 0) ? 0 : pagesize; // console.log(pagesize) var offset = pagesize * limit; //跳過的數目 var startTm = $('.startTm').val(); var endTm = $('.endTm').val(); var data1 = { startTm: startTm, endTm: endTm, offset: offset } ajax(data1); }) // 日期選擇表單 $('#choose button').click(function () { pagesize=0; var startTm = $('.startTm').val(); var endTm = $('.endTm').val(); var data1 = { startTm: startTm, endTm: endTm, offset: 0 } $("#table tr").not($("#table tr:first")).remove(); ajax(data1); }); // 當前時間的函式 /* * @param param string 確定時間的顯示格式 'ymd' => 年-月-日 * 其它 => 年-月-日+時:分:秒 * @param num num +1代表後一天,-1代表前一天 * **/ function getFormatDate(param, num = 0) { var date = new Date(); var seperator1 = "-"; var seperator2 = ":"; var seperator3 = '+'; var y = date.getFullYear(); var m = date.getMonth() + 1; var d = date.getDate() + num; var h = date.getHours(); var i = date.getMinutes(); var s = date.getSeconds(); if (m >= 1 && m <= 9) { m = "0" + m; } d = d <= 0 ? 1 : d; if (d >= 0 && d <= 9) { d = "0" + d; } if (param = 'ymd') { var currentdate = y + seperator1 + m + seperator1 + d; } else { var currentdate = y + seperator1 + m + seperator1 + d + seperator3 + h + seperator2 + i + seperator2 + s; } return currentdate; } // 顯示聊天內容 $(document).on('click', '.convId', function () { var convId = $(this).find('span').text(); var data1 = { conv_id: convId } $.ajax({ url: "php/conv.php", data: data1, success: function (data) { var newJson = (new Function("", "return " + data))(data).result; // console.log(newJson) $('.convBox h6 span').text(convId); $('.convBox .agent_name span').text(newJson.agent_name); $('.convBox .wait_in_secs span').text(newJson.wait_in_secs); $('.convBox .visitor_ip span').text(newJson.visitor_ip); $('.convBox .visitor_location span').text(newJson.visitor_location); $('.convBox .search_engine_kw span').text(newJson.search_engine_kw); $('.convBox .conv_end_tm span').text(newJson.conv_end_tm); $('.convBox .conv_start_tm span').text(newJson.conv_start_tm); $('.convBox .visitor_location span').text(newJson.visitor_location); let convLen = newJson.conv_content.length; let conv_content = []; // console.log(convLen) for (let j = 0; j < convLen; j++) { // conv_content.push(111) conv_content.push('<div class="' + newJson.conv_content[j].from + '"><p>' + newJson.conv_content[j].timestamp + '</p>' + newJson.conv_content[j].content + '</div>'); } // console.log(conv_content) $('.convBox .mainCon').html(conv_content.join('')); } }); $('.convBox').show(); }) $(document).on('click', '.convBox .close', function () { $('.convBox').hide(); }); // 列印 $('#export').click(function () { if ($('.page span').text() == '已經是最後一頁') { // method1(tableList,'聊天資料'); method1(tableList,'1.xlsx'); return false; } pageAll =pagesize; allrecord(); // method1(allrecord(),'美洽對話'); }) }); </script> <script type="text/javascript" language="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 method1(tableid,name="1.xlsx") { //整個表格拷貝到EXCEL中 if (getExplorer() == 'ie') { var curTbl = document.getElementById(tableid); var oXL = new ActiveXObject("Excel.Application"); //建立AX物件excel var oWB = oXL.Workbooks.Add(); //獲取workbook物件 var xlsheet = oWB.Worksheets(1); //啟用當前sheet var sel = document.body.createTextRange(); sel.moveToElementText(curTbl); //把表格中的內容移到TextRange中 sel.select; //全選TextRange中內容 sel.execCommand("Copy"); //複製TextRange中內容 xlsheet.Paste(); //貼上到活動的EXCEL中 oXL.Visible = true; //設定excel可見屬性 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); //xls.visible = false; oXL.Quit(); oXL = null; //結束excel程序,退出完成 //window.setInterval("Cleanup();",1); idTmr = window.setInterval("Cleanup();", 1); } } else { tableToExcel(tableid,name) } } function Cleanup() { window.clearInterval(idTmr); CollectGarbage(); } 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><!--[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) { var ctx = {worksheet:name , table:table} // console.log(uri + base64(format(template, ctx))) // return; // $('#export').attr('href',uri + base64(format(template, ctx))) window.location.href = uri + base64(format(template, ctx)); } })() </script> </body> </html>