方案一:支持IEjavascript
//導出excel function exportExcel(DivID,strTitle){ if(DivID==null) { return false; } var jXls, myWorkbook, myWorksheet; try { jXls = new ActiveXObject('Excel.Application'); } catch (e) { alert("沒法啓動Excel!\n\n若是您確信您的電腦中已經安裝了Excel,"+"那麼請調整IE的安全級別。\n\n具體操做:\n\n"+"工具 → Internet選項 → 安全 → 自定義級別 → 對 沒有標記爲安全的ActiveX進行初始化和腳本運行 → 啓用"); return false; } jXls.DisplayAlerts = false; myWorkbook = jXls.Workbooks.Add(); var curTb = document.getElementById(DivID); myWorksheet = myWorkbook.ActiveSheet; myWorksheet.name=strTitle; var sel = document.body.createTextRange(); sel.moveToElementText(curTb); sel.select(); window.clipboardData.setData('text',''); sel.execCommand("Copy"); myWorksheet.Paste(); jXls.Visible = true; try{ var fname = jXls.Application.GetSaveAsFilename("OA數據"+strTitle+".xls", "Excel Spreadsheets (*.xls), *.xls"); }catch(e){ print("Nested catch caught " + e); } finally{ if(fname!=false) { myWorkbook .SaveAs(fname); alert("數據成功保存在:"+fname); } } // myWorkbook .Close(savechanges=false); // jXls.Quit(); window.clipboardData.setData('text',''); jXls = null; myWorkbook = null; myWorksheet = null; }
<table class="oa-el-grid-list" id="tb" style="width:99%" cellspacing="0" cellpadding="0" border="0"> <thead> <%=tab_html%> </thead> <%=TableHtml %> </table> <input id="btnSavExcel" onclick="exportExcel('tb','……表')" type="button" value="導出" />
方案2html
<input type="button" onclick="tableToExcel('tablename', 'name')" value="Export to Excel">
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) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })()
方案3java
<a id="dlink" style="display:none;"></a> <input type="button" onclick="tableToExcel('tablename', 'name', 'myfile.xls')" value="Export to Excel">
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, filename) { if (!table.nodeType) table = document.getElementById(table) var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML } document.getElementById("dlink").href = uri + base64(format(template, ctx)); document.getElementById("dlink").download = filename; document.getElementById("dlink").click(); } })()
支持:Chrome、Firefox、Opera、Safarinode
根據Json導出Exceljquery
; !function () { layui.use(['layer', 'element'], function () { var tableTitle = [{ "value": "行政區", "type": "ROW_HEADER_HEADER", "datatype": "string" }, { "value": "留守兒童(人)", "type": "ROW_HEADER_HEADER", "datatype": "string" }, { "value": "困境兒童(人)", "type": "ROW_HEADER_HEADER", "datatype": "string" },{"value": "合計(人)", "type": "ROW_HEADER_HEADER", "datatype": "string" }] $(".querynav a:eq(2)").click(function (param) { var tableData=[]; layer.confirm("確認導出當前頁數據?",function(params) { $.each($(".tableBody tr"),function (i,lay) { var data=[]; layer.closeAll(); for(i=0;i<$(this).children().length;i++){ var a="{value:'"+$(this).children().eq(i).text()+"',type:'ROW_HEADER'}"; data.push( eval("(" + a + ")")); } tableData.push(data); console.log(data.toString()); }); console.log(tableData.toString()); var cityName=""; if ($("#Town").val() != "") { civilregionalismcode += 'civilregionalismcode=' + $("#Town").val(); } else if ($("#Country").val() != "") { civilregionalismcode += 'civilregionalismcode=' + $("#Country").val(); } else if ($("#city").val() != "") { civilregionalismcode += 'civilregionalismcode=' + $("#city").val(); } else if ($("#province").val() != "") { civilregionalismcode += 'civilregionalismcode=' + $("#province").val(); } // return; JSONToExcelConvertor(tableData, "測試數據", tableTitle) }) }); function JSONToExcelConvertor(JSONData, FileName, ShowLabel) { //先轉化json var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData; var excel = '<table>'; //設置表頭 var row = "<tr>"; for (var i = 0, l = ShowLabel.length; i < l; i++) { row += "<td>" + ShowLabel[i].value + '</td>'; } //換行 excel += row + "</tr>"; console.log(arrData); // return; //設置數據 for (var i = 0; i < arrData.length; i++) { var row = "<tr>"; for (var index in arrData[i]) { var value = arrData[i][index].value === "." ? "" : arrData[i][index].value; row += '<td>' + value + '</td>'; } excel += row + "</tr>"; } excel += "</table>"; 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 += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">'; excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel'; excelFile += '; charset=UTF-8">'; excelFile += "<head>"; excelFile += "<!--[if gte mso 9]>"; excelFile += "<xml>"; excelFile += "<x:ExcelWorkbook>"; excelFile += "<x:ExcelWorksheets>"; excelFile += "<x:ExcelWorksheet>"; excelFile += "<x:Name>"; excelFile += "{worksheet}"; excelFile += "</x:Name>"; excelFile += "<x:WorksheetOptions>"; excelFile += "<x:DisplayGridlines/>"; excelFile += "</x:WorksheetOptions>"; excelFile += "</x:ExcelWorksheet>"; excelFile += "</x:ExcelWorksheets>"; excelFile += "</x:ExcelWorkbook>"; excelFile += "</xml>"; excelFile += "<![endif]-->"; excelFile += "</head>"; excelFile += "<body>"; excelFile += excel; excelFile += "</body>"; excelFile += "</html>"; var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile); var link = document.createElement("a"); link.href = uri; link.style = "visibility:hidden"; link.download = FileName + ".xls"; document.body.appendChild(link); link.click(); document.body.removeChild(link); } }) } ()
方案4:git
/*將JqGrid導出Excel(中文)*/ <script src="/UILib/tableExport.jquery.plugin-master/libs/FileSaver/FileSaver.min.js"></script> <script src="/UILib/tableExport.jquery.plugin-master/tableExport.min.js"></script> <script type="text/javascript"> //導出數據 function ExportData() { var tbId = "datagrid"; //var $tb = $("#" + tbId).clone(); var $tbst = $("table[aria-labelledby='gbox_" + tbId + "']"); $tbst.find("td:hidden").remove(); var $tbs = $tbst.clone(); $tbs.find("span").remove(); var $tb; if ($tbs.length > 1) { var $tbody = $($tbs[1]).children("tbody"); $tbody.children("tr[class='jqgfirstrow']").remove(); $($tbs[0]).append($tbody); $tb = $($tbs[0]); //$tb.children("tbody tr[class='jqgfirstrow']").remove(); $tb.children("thead").children("tr[class='jqg-first-row-header']"); $tb.attr("id", "tb_Temp_Export"); //$tb.hide();//隱藏以後出現導出爲空 var $div = $("<div style='width:0px;height:0px;overflow:hidden;z-index:-1;'></div>").append($tb); $(document.body).append($div); var tbRepName = "數據報表"; var exName = tbRepName;//+ "(" + $('#txtSTime').val() + ")"; $tb.tableExport({ fileName: exName, type: 'excel', worksheetName: [tbRepName] , mso: { styles: ['background-color', 'background', 'color', 'font-family', 'font-size', 'font-weight', 'text-align', 'height', 'width'] } }); setTimeout(function () { $div.remove(); }, 2000); } else { alert("操做失敗,請刷新後重試!"); } } </script>
注:加入styles樣式時,可能會導出報錯github
其它案例:json
HTML用JS導出Excel的五種方法bootstrap
git_demo
https://github.com/kayalshri/tableExport.jquery.plugin/blob/master/tableExport.js