js前端導出excel:json形式的導出


第一中形式的導出:主要是表頭對應主體數據,json形式的導出

js庫文件名稱 : table2excel.js

這個js庫文件是網上找的,並且自己根據自己業務需求把內容改了一下
復制到 table2excel.js 文件中,作為自己的js庫,就可以使用。記得先引入jq的庫

/*
* jQuery table2excel - v1.1.1 * jQuery plugin to export an .xls file in browser from an HTML table * https://github.com/rainabba/jquery-table2excel * * Made by rainabba * Under MIT License */ /* * jQuery table2excel - v1.1.1 * jQuery plugin to export an .xls file in browser from an HTML table * https://github.com/rainabba/jquery-table2excel * * Made by rainabba * Under MIT License * * *把所有的樣式移除了 * 這里是以json的形式來導出excel的 */ //table2excel.js ;(function ( $, window, document, undefined ) { var pluginName = "table2excel", defaults = { filename: "table2excel",//導出excel的名字 fileext: ".xls",//導出excel的格式 sheetName:"sheet",//sheet的名字 // excludeFirst:false,//是否去除第一列,默認去不掉 //excudeLast:false,//最后一列是否除去 dataList:[],//數據,json數組 必填 dataTitle:{}//表格的頭 必填 }; // The actual plugin constructor function Plugin ( element, options ) { this.element = element; // jQuery has an extend method which merges the contents of two or // more objects, storing the result in the first object. The first object // is generally empty as we don't want to alter the default options for // future instances of the plugin //extend把后倆個合並到第一個中 this.settings = $.extend( {}, defaults, options ); this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function () { var e = this; var utf8Heading = "<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=UTF-8\">"; e.template = { head: "<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\">" + utf8Heading + "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>", sheet: { head: "<x:ExcelWorksheet><x:Name>", tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>" }, mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>", table: { head: "<table>", tail: "</table>" }, foot: "</body></html>" }; e.tableRows = []; if(e.settings.dataTitle.length < 0 || e.settings.dataTitle == ""){ console.log("不可以沒有title"); return false; } var tempRowsTitle = ""; //標題行 tempRowsTitle += "<tr>"; for(var key in e.settings.dataTitle){ tempRowsTitle += "<td>" + e.settings.dataTitle[key] + "</td>"; } tempRowsTitle += "</tr>"; e.tableRows.push(tempRowsTitle); //循環數據行 var listNum = e.settings.dataList.length; var list = e.settings.dataList; for(var i=0; i < Number(listNum); i++ ){ var tempRows = ""; tempRows += "<tr>"; for(var key in e.settings.dataTitle){ tempRows += "<td>" + (typeof(list[i][key]) == "undefined" ? "--" : list[i][key] == null ? "--" : list[i][key]) + "</td>"; } tempRows += "</tr>"; //每行都添加到里邊 e.tableRows.push(tempRows); } e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName); }, tableToExcel: function (table, name, sheetName) { var e = this, fullTemplate="", i, link, a; e.format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }); }; sheetName = typeof sheetName === "undefined" ? "Sheet" : sheetName; e.ctx = { // worksheet: name || "Worksheet",//這個字段無用 table: table, sheetName: sheetName }; fullTemplate= e.template.head; if ( $.isArray(table) ) { for (i in table) { //fullTemplate += e.template.sheet.head + "{" + e.ctx.worksheet + i + "}" + e.template.sheet.tail; fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail; } } fullTemplate += e.template.mid; if ( $.isArray(table) ) { for (i in table) { fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail; } } fullTemplate += e.template.foot; for (i in table) { e.ctx["table" + i] = table[i]; } delete e.ctx.table; var isIE = /*@cc_on!@*/false || !!document.documentMode; // this works with IE10 and IE11 both :) //if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // this works ONLY with IE 11!!! if (isIE) { if (typeof Blob !== "undefined") { //use blobs if we can fullTemplate = e.format(fullTemplate, e.ctx); // with this, works with IE fullTemplate = [fullTemplate]; //convert to array var blob1 = new Blob(fullTemplate, { type: "text/html" }); window.navigator.msSaveBlob(blob1, getFileName(e.settings) ); } else { //otherwise use the iframe and save //requires a blank iframe on page called txtArea1 txtArea1.document.open("text/html", "replace"); txtArea1.document.write(e.format(fullTemplate, e.ctx)); txtArea1.document.close(); txtArea1.focus(); sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings) ); } } else { var blob = new Blob([e.format(fullTemplate, e.ctx)], {type: "application/vnd.ms-excel"}); window.URL = window.URL || window.webkitURL; link = window.URL.createObjectURL(blob); a = document.createElement("a"); a.download = getFileName(e.settings); a.href = link; document.body.appendChild(a); a.click(); document.body.removeChild(a); } return true; } }; function getFileName(settings) { return ( settings.filename ? settings.filename : "table2excel" ); } // Removes all img tags function exclude_img(string) { var _patt = /(\s+alt\s*=\s*"([^"]*)"|\s+alt\s*=\s*'([^']*)')/i; return string.replace(/<img[^>]*>/gi, function myFunction(x){ var res = _patt.exec(x); if (res !== null && res.length >=2) { return res[2]; } else { return ""; } }); } // Removes all link tags function exclude_links(string) { return string.replace(/<a[^>]*>|<\/a>/gi, ""); } // Removes input params function exclude_inputs(string) { var _patt = /(\s+value\s*=\s*"([^"]*)"|\s+value\s*=\s*'([^']*)')/i; return string.replace(/<input[^>]*>|<\/input>/gi, function myFunction(x){ var res = _patt.exec(x); if (res !== null && res.length >=2) { return res[2]; } else { return ""; } }); } $.fn[ pluginName ] = function ( options ) { var e = this; e.each(function() { //console.log(options) if ( !$.data( e, "plugin_" + pluginName ) ) { $.data( e, "plugin_" + pluginName, new Plugin( this, options ) ); } }); // chain jQuery functions return e; }; })( jQuery, window, document );
根據自己的業務寫的一個調用上邊庫的js工具
20181025 這的settings是全局的變量,多個方法調用的導出的時候,會導致並發問題
下邊會加一個再次修改的

建議:不要使用這個,使用下邊的方法這個后邊的一個方法

var
App ={ //導出配置的參數 settings : { //頁數 pageInt : 1, //每次限制10條 limit : 10, //拿到的數據json進行封裝到arr數組中 arr : [] }, //導出excel時候,把頁面的數據分裝到一個json數組中,主要針對導出數據時候分頁多次查詢,例如吧:每次查詢10條數據,那么這里會循環很多次,每次獲取10條數據,封裝起來,然后自請求。。。直到把所有的數據拿到,然后執行導出 exportExcel : function (url, excelTitleJson, excelName, data) { if(typeof(data) == "undefined" || data == null){ console.log("查詢條件為空"); data = JSON.parse("{}"); } //默認第一頁開始導出 data["page"] = App.settings.pageInt; $.getJSON(url, data, function(json){ if(json.data.length <= 0){ //沒有查到數據,不導出 if(App.settings.arr.length > 0){ //table.exportFile([],App.settings.arr , 'xls'); //默認導出 csv,也可以為:xls //這里隨意找個類就可以,暫時不會改,但是這樣是可以使用的 $(".layui-table-box").table2excel({ //exclude: ".noExl", filename: excelName + new Date().toISOString().replace(/[\-\:\.]/g, ""), fileext: ".xls", sheetName: "sheet", // excludeFirst:true, // excudeLast:true, dataList:App.settings.arr,//這個是后台獲取到的數據,針對對此分頁獲取數據 dataTitle:excelTitleJson }); //導出后這個頁數,初始化 page:App.settings.pageInt = 1; } }else{ for(var i = 0;i<json.data.length;i++){ App.settings.arr.push(json.data[i]); } App.settings.pageInt++; data["page"] = App.settings.pageInt; //有數據,就再次執行拿數據 App.exportExcel(url, excelTitleJson, excelName, data); } }); } }

 

調整后的代碼,把並發的問題修改了。師兄幫助修改的。自己是沒有發現的

var
App ={ //導出excel時候,把頁面的數據分裝到一個json數組中,然后使用layui的導出方法導出數據 exportExcel : function (url, excelTitleJson, excelName, data, settings) { if(typeof(data) == "undefined" || data == null){ console.log("查詢條件為空"); data = JSON.parse("{}"); } if(! settings){ settings = { //頁數 pageInt : 1, //每次限制10條 limit : 10, //拿到的數據json進行封裝到arr數組中 arr : [] } } data["page"] = settings.pageInt; $.getJSON(url, data, function(json){ if(json.data.length <= 0){ //沒有查到數據,不導出 if(settings.arr.length > 0){ //table.exportFile([],settings.arr , 'xls'); //默認導出 csv,也可以為:xls $(".layui-table-box").table2excel({ //exclude: ".noExl", filename: excelName + new Date().toISOString().replace(/[\-\:\.]/g, ""), fileext: ".xls", sheetName: "sheet", excludeFirst:true, excudeLast:true, dataList:settings.arr, dataTitle:excelTitleJson }); //導出后這個頁數,初始化 page:settings.pageInt = 1; } }else{ for(var i = 0;i<json.data.length;i++){ settings.arr.push(json.data[i]); } settings.pageInt++; data["page"] = settings.pageInt; //有數據,就再次執行拿數據,回調 App.exportExcel(url, excelTitleJson, excelName, data, settings); } }); } }

 

 

 

最后就是使用了

 

App.exportExcel("/YunApps/com_momathink_crm_zkhq/customer/myCustomerList",
{"followStatus":"狀態"}, //這里需要填寫的是excel導出后的表頭,key就是數據庫查詢出的json數據的每條數據的key,value就是表頭,每個表頭會對應上它的值
"客戶信息",//導出excel的名字
{}//
最后一個參數可填可不填
); 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM