1. 第一中形式的导出:主要是表头对应主体数据,json形式的导出
  2. js库文件名称 table2excel.js
    这个js库文件是网上找的,并且自己根据自己业务需求把内容改了一下
    复制到 table2excel.js 文件中,作为自己的js库,就可以使用。记得先引入jq的库
  1. /*
  2. * jQuery table2excel - v1.1.1
  3. * jQuery plugin to export an .xls file in browser from an HTML table
  4. * https://github.com/rainabba/jquery-table2excel
  5. *
  6. * Made by rainabba
  7. * Under MIT License
  8. */
  9. /*
  10. * jQuery table2excel - v1.1.1
  11. * jQuery plugin to export an .xls file in browser from an HTML table
  12. * https://github.com/rainabba/jquery-table2excel
  13. *
  14. * Made by rainabba
  15. * Under MIT License
  16. *
  17. * *把所有的样式移除了
  18. * 这里是以json的形式来导出excel的
  19. */
  20. //table2excel.js
  21. ;(function ( $, window, document, undefined ) {
  22. var pluginName = "table2excel",
  23.  
  24. defaults = {
  25. filename: "table2excel",//导出excel的名字
  26. fileext: ".xls",//导出excel的格式
  27. sheetName:"sheet",//sheet的名字
  28. // excludeFirst:false,//是否去除第一列,默认去不掉
  29. //excudeLast:false,//最后一列是否除去
  30. dataList:[],//数据,json数组 必填
  31. dataTitle:{}//表格的头 必填
  32. };
  33.  
  34. // The actual plugin constructor
  35. function Plugin ( element, options ) {
  36. this.element = element;
  37. // jQuery has an extend method which merges the contents of two or
  38. // more objects, storing the result in the first object. The first object
  39. // is generally empty as we don't want to alter the default options for
  40. // future instances of the plugin
  41. //extend把后俩个合并到第一个中
  42. this.settings = $.extend( {}, defaults, options );
  43. this._defaults = defaults;
  44. this._name = pluginName;
  45. this.init();
  46. }
  47.  
  48. Plugin.prototype = {
  49. init: function () {
  50. var e = this;
  51.  
  52. var utf8Heading = "<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=UTF-8\">";
  53. e.template = {
  54. 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>",
  55. sheet: {
  56. head: "<x:ExcelWorksheet><x:Name>",
  57. tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
  58. },
  59. mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>",
  60. table: {
  61. head: "<table>",
  62. tail: "</table>"
  63. },
  64. foot: "</body></html>"
  65. };
  66.  
  67. e.tableRows = [];
  68.  
  69. if(e.settings.dataTitle.length < 0 || e.settings.dataTitle == ""){
  70. console.log("不可以没有title");
  71. return false;
  72. }
  73. var tempRowsTitle = "";
  74. //标题行
  75. tempRowsTitle += "<tr>";
  76. for(var key in e.settings.dataTitle){
  77. tempRowsTitle += "<td>" + e.settings.dataTitle[key] + "</td>";
  78. }
  79. tempRowsTitle += "</tr>";
  80. e.tableRows.push(tempRowsTitle);
  81.  
  82. //循环数据行
  83. var listNum = e.settings.dataList.length;
  84. var list = e.settings.dataList;
  85. for(var i=0; i < Number(listNum); i++ ){
  86. var tempRows = "";
  87. tempRows += "<tr>";
  88. for(var key in e.settings.dataTitle){
  89. tempRows += "<td>" + (typeof(list[i][key]) == "undefined" ? "--" : list[i][key] == null ? "--" : list[i][key]) + "</td>";
  90. }
  91. tempRows += "</tr>";
  92. //每行都添加到里边
  93. e.tableRows.push(tempRows);
  94. }
  95.  
  96. e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName);
  97. },
  98.  
  99. tableToExcel: function (table, name, sheetName) {
  100. var e = this, fullTemplate="", i, link, a;
  101.  
  102. e.format = function (s, c) {
  103. return s.replace(/{(\w+)}/g, function (m, p) {
  104. return c[p];
  105. });
  106. };
  107.  
  108. sheetName = typeof sheetName === "undefined" ? "Sheet" : sheetName;
  109.  
  110. e.ctx = {
  111. // worksheet: name || "Worksheet",//这个字段无用
  112. table: table,
  113. sheetName: sheetName
  114. };
  115.  
  116. fullTemplate= e.template.head;
  117.  
  118. if ( $.isArray(table) ) {
  119. for (i in table) {
  120. //fullTemplate += e.template.sheet.head + "{" + e.ctx.worksheet + i + "}" + e.template.sheet.tail;
  121. fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;
  122. }
  123. }
  124.  
  125. fullTemplate += e.template.mid;
  126.  
  127. if ( $.isArray(table) ) {
  128. for (i in table) {
  129. fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail;
  130. }
  131. }
  132.  
  133. fullTemplate += e.template.foot;
  134.  
  135. for (i in table) {
  136. e.ctx["table" + i] = table[i];
  137. }
  138. delete e.ctx.table;
  139.  
  140. var isIE = /*@cc_on!@*/false || !!document.documentMode; // this works with IE10 and IE11 both :)
  141. //if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // this works ONLY with IE 11!!!
  142. if (isIE) {
  143. if (typeof Blob !== "undefined") {
  144. //use blobs if we can
  145. fullTemplate = e.format(fullTemplate, e.ctx); // with this, works with IE
  146. fullTemplate = [fullTemplate];
  147. //convert to array
  148. var blob1 = new Blob(fullTemplate, { type: "text/html" });
  149. window.navigator.msSaveBlob(blob1, getFileName(e.settings) );
  150. } else {
  151. //otherwise use the iframe and save
  152. //requires a blank iframe on page called txtArea1
  153. txtArea1.document.open("text/html", "replace");
  154. txtArea1.document.write(e.format(fullTemplate, e.ctx));
  155. txtArea1.document.close();
  156. txtArea1.focus();
  157. sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings) );
  158. }
  159.  
  160. } else {
  161. var blob = new Blob([e.format(fullTemplate, e.ctx)], {type: "application/vnd.ms-excel"});
  162. window.URL = window.URL || window.webkitURL;
  163. link = window.URL.createObjectURL(blob);
  164. a = document.createElement("a");
  165. a.download = getFileName(e.settings);
  166. a.href = link;
  167.  
  168. document.body.appendChild(a);
  169.  
  170. a.click();
  171.  
  172. document.body.removeChild(a);
  173. }
  174.  
  175. return true;
  176. }
  177. };
  178.  
  179. function getFileName(settings) {
  180. return ( settings.filename ? settings.filename : "table2excel" );
  181. }
  182.  
  183. // Removes all img tags
  184. function exclude_img(string) {
  185. var _patt = /(\s+alt\s*=\s*"([^"]*)"|\s+alt\s*=\s*'([^']*)')/i;
  186. return string.replace(/<img[^>]*>/gi, function myFunction(x){
  187. var res = _patt.exec(x);
  188. if (res !== null && res.length >=2) {
  189. return res[2];
  190. } else {
  191. return "";
  192. }
  193. });
  194. }
  195.  
  196. // Removes all link tags
  197. function exclude_links(string) {
  198. return string.replace(/<a[^>]*>|<\/a>/gi, "");
  199. }
  200.  
  201. // Removes input params
  202. function exclude_inputs(string) {
  203. var _patt = /(\s+value\s*=\s*"([^"]*)"|\s+value\s*=\s*'([^']*)')/i;
  204. return string.replace(/<input[^>]*>|<\/input>/gi, function myFunction(x){
  205. var res = _patt.exec(x);
  206. if (res !== null && res.length >=2) {
  207. return res[2];
  208. } else {
  209. return "";
  210. }
  211. });
  212. }
  213.  
  214. $.fn[ pluginName ] = function ( options ) {
  215. var e = this;
  216. e.each(function() {
  217. //console.log(options)
  218. if ( !$.data( e, "plugin_" + pluginName ) ) {
  219. $.data( e, "plugin_" + pluginName, new Plugin( this, options ) );
  220. }
  221. });
  222.  
  223. // chain jQuery functions
  224. return e;
  225. };
  226.  
  227. })( jQuery, window, document );
  1. 根据自己的业务写的一个调用上边库的js工具
    20181025 这的settings是全局的变量,多个方法调用的导出的时候,会导致并发问题
    下边会加一个再次修改的
  2.  
  3. 建议:不要使用这个,使用下边的方法这个后边的一个方法
  4.  
  5. var App ={
  6. //导出配置的参数
  7. settings : {
  8. //页数
  9. pageInt : 1,
  10. //每次限制10条
  11. limit : 10,
  12. //拿到的数据json进行封装到arr数组中
  13. arr : []
  14. },
  15.  
  16. //导出excel时候,把页面的数据分装到一个json数组中,主要针对导出数据时候分页多次查询,例如吧:每次查询10条数据,那么这里会循环很多次,每次获取10条数据,封装起来,然后自请求。。。直到把所有的数据拿到,然后执行导出
  17. exportExcel : function (url, excelTitleJson, excelName, data) {
  18. if(typeof(data) == "undefined" || data == null){
  19. console.log("查询条件为空");
  20. data = JSON.parse("{}");
  21. }
  22. //默认第一页开始导出
  23. data["page"] = App.settings.pageInt;
  24. $.getJSON(url, data, function(json){
  25. if(json.data.length <= 0){
  26. //没有查到数据,不导出
  27. if(App.settings.arr.length > 0){
  28. //table.exportFile([],App.settings.arr , 'xls'); //默认导出 csv,也可以为:xls
  29. //这里随意找个类就可以,暂时不会改,但是这样是可以使用的
  30. $(".layui-table-box").table2excel({
  31. //exclude: ".noExl",
  32. filename: excelName + new Date().toISOString().replace(/[\-\:\.]/g, ""),
  33. fileext: ".xls",
  34. sheetName: "sheet",
  35. // excludeFirst:true,
  36. // excudeLast:true,
  37. dataList:App.settings.arr,//这个是后台获取到的数据,针对对此分页获取数据
  38. dataTitle:excelTitleJson
  39. });
  40.  
  41. //导出后这个页数,初始化
  42. page:App.settings.pageInt = 1;
  43. }
  44. }else{
  45. for(var i = 0;i<json.data.length;i++){
  46. App.settings.arr.push(json.data[i]);
  47. }
  48. App.settings.pageInt++;
  49. data["page"] = App.settings.pageInt;
  50.  
  51. //有数据,就再次执行拿数据
  52. App.exportExcel(url, excelTitleJson, excelName, data);
  53. }
  54. });
  55. }
  56. }
  1. 调整后的代码,把并发的问题修改了。师兄帮助修改的。自己是没有发现的
  2.  
  3. var App ={
  4. //导出excel时候,把页面的数据分装到一个json数组中,然后使用layui的导出方法导出数据
  5. exportExcel : function (url, excelTitleJson, excelName, data, settings) {
  6. if(typeof(data) == "undefined" || data == null){
  7. console.log("查询条件为空");
  8. data = JSON.parse("{}");
  9. }
  10.  
  11. if(! settings){
  12. settings = {
  13. //页数
  14. pageInt : 1,
  15. //每次限制10条
  16. limit : 10,
  17. //拿到的数据json进行封装到arr数组中
  18. arr : []
  19. }
  20. }
  21.  
  22. data["page"] = settings.pageInt;
  23. $.getJSON(url, data, function(json){
  24. if(json.data.length <= 0){
  25. //没有查到数据,不导出
  26. if(settings.arr.length > 0){
  27. //table.exportFile([],settings.arr , 'xls'); //默认导出 csv,也可以为:xls
  28.  
  29. $(".layui-table-box").table2excel({
  30. //exclude: ".noExl",
  31. filename: excelName + new Date().toISOString().replace(/[\-\:\.]/g, ""),
  32. fileext: ".xls",
  33. sheetName: "sheet",
  34. excludeFirst:true,
  35. excudeLast:true,
  36. dataList:settings.arr,
  37. dataTitle:excelTitleJson
  38. });
  39.  
  40. //导出后这个页数,初始化
  41. page:settings.pageInt = 1;
  42. }
  43. }else{
  44. for(var i = 0;i<json.data.length;i++){
  45. settings.arr.push(json.data[i]);
  46. }
  47. settings.pageInt++;
  48. data["page"] = settings.pageInt;
  49.  
  50. //有数据,就再次执行拿数据,回调
  51. App.exportExcel(url, excelTitleJson, excelName, data, settings);
  52. }
  53. });
  54. }
  55. }

最后就是使用了

  1. App.exportExcel("/YunApps/com_momathink_crm_zkhq/customer/myCustomerList",
    {"followStatus":"状态"}, //这里需要填写的是excel导出后的表头,key就是数据库查询出的json数据的每条数据的key,value就是表头,每个表头会对应上它的值
    "客户信息",//导出excel的名字
    {}//最后一个参数可填可不填
  1. );

js前端导出excel:json形式的导出的更多相关文章

  1. .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)

    .Net MVC  导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构)   public cl ...

  2. Java POI 导出EXCEL经典实现 Java导出Excel

    转自http://blog.csdn.net/evangel_z/article/details/7332535 在web开发中,有一个经典的功能,就是数据的导入导出.特别是数据的导出,在生产管理或者 ...

  3. poi 实战代码---导出Excel(根据模板导出)

    /** * 导出excel * @param request * @param response * @return * @throws Exception */ @RequestMapping(&q ...

  4. laravel-admin 自定义导出excel功能,并导出图片

    https://www.jianshu.com/p/91975f66427d 最近用laravel-admin在做一个小项目,其中用到了excel导出功能. 但是laravel-admin自带的导出功 ...

  5. java解决poi导出excel文字水印,导出excel不可操作问题

    首先需求是用户提出导出excel数据需使用水印备注其用途: 其实就是在导出excel的同时带有自定义文字水印的导出. 那么我们首先想到的肯定是以一个什么样的思路去解决该问题,首先查找poi导出exce ...

  6. Java导出Excel(有数据库导出代码)

    /** * 导出 * @param request * @param response * @throws Exception */ @SuppressWarnings("unchecked ...

  7. C# 导出 excel 复杂格式 html导出

    /// <summary> /// 夜班津贴统计导出 /// </summary> public void ExportOtStat(string data) { var in ...

  8. js前端解析excel文件

    使用纯Javascript解析excel文件. 使用的是开源的解析excel的js库:sheetjs.github地址:https://github.com/SheetJS/js-xlsx 首先引用J ...

  9. 导出excel(利用工具类导出excel)

    /** * 添加导出功能 * @param creditPageResult * @param request * @param response */ @RequestMapping(value = ...

随机推荐

  1. NRF51822之FICR

    uint32_t deviceID[2];union{    uint32_t  DW;    uint8_t   B[4];} device_ID;//read device ID deviceID ...

  2. Oracle修改表或者字段的注释

    转自:https://www.cnblogs.com/fx-blog/p/7132833.html 语句:comment on table 表名 is '表的注释信息'; comment on col ...

  3. System.Types.hpp(77): E2029 'TObject' must be a previously defined class or struct

    System.Types.hpp System.Types.hpp(77): E2029 'TObject' must be a previously defined class or struct ...

  4. mingw 设置python 设置git环境变量

    1.python路径设置: 安装python 比如目录:C:\Python27 假如mingw安装C盘根目录下的话,进入下面目录:C:\MinGW\msys\1.0\etc 找到 fstab 文件修改 ...

  5. 学习别人的rpc框架

    https://my.oschina.net/huangyong/blog/361751 https://gitee.com/huangyong/rpc 在此文基础上的另一个实现,解决了原文中一些问题 ...

  6. Sonya and Exhibition 1004B

    B. Sonya and Exhibition time limit per test 1 second memory limit per test 256 megabytes input stand ...

  7. linux内核中的const成员是否可以修改?

    本文的基础知识:由于前半部分内容是转的,且不知道原文出处,没法给出原文地址,大家自行百度 const的实现机制 const究竟是如何实现的呢?对于声明为const的内置类型,例如int,short,l ...

  8. Spring+Quartz 实现定时任务的配置方法

    Spring+Quartz 实现定时任务的配置方法 整体介绍 一.Quartz介绍 在企业应用中,我们经常会碰到时间任务调度的需求,比如每天凌晨生成前天报表,每小时生成一次汇总数据等等.Quartz是 ...

  9. Java如何创建参数个数不限的函数

    可变的参数类型,也称为不定参数类型.英文缩写是varargus,还原一下就是variable argument type.通过它的名字可以很直接地看出来,这个方法在接收参数的时候,个数是不定的. pu ...

  10. spring boot 集成Thymeleaf