• 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+alts*=s*"([^"]*)"|s+alts*=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+values*=s*"([^"]*)"|s+values*=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的名字
    {}//
    最后一个参数可填可不填
    ); 
  • 相关阅读:
    《显示器件应用分析精粹》构思
    《三极管应用分析精粹》已经交稿
    leetcode
    mskitten
    如果IBM再给我一次实习机会
    “完美工作”是什么样子
    一起四十岁退休吧……
    未来公司的酒会
    热泪盈眶的五十岁 | James Altucher
    一个程序员的辞呈
  • 原文地址:https://www.cnblogs.com/renjianjun/p/9845733.html
Copyright © 2020-2023  润新知