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的名字
{}//最后一个参数可填可不填
- );
js前端导出excel:json形式的导出的更多相关文章
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
- Java POI 导出EXCEL经典实现 Java导出Excel
转自http://blog.csdn.net/evangel_z/article/details/7332535 在web开发中,有一个经典的功能,就是数据的导入导出.特别是数据的导出,在生产管理或者 ...
- poi 实战代码---导出Excel(根据模板导出)
/** * 导出excel * @param request * @param response * @return * @throws Exception */ @RequestMapping(&q ...
- laravel-admin 自定义导出excel功能,并导出图片
https://www.jianshu.com/p/91975f66427d 最近用laravel-admin在做一个小项目,其中用到了excel导出功能. 但是laravel-admin自带的导出功 ...
- java解决poi导出excel文字水印,导出excel不可操作问题
首先需求是用户提出导出excel数据需使用水印备注其用途: 其实就是在导出excel的同时带有自定义文字水印的导出. 那么我们首先想到的肯定是以一个什么样的思路去解决该问题,首先查找poi导出exce ...
- Java导出Excel(有数据库导出代码)
/** * 导出 * @param request * @param response * @throws Exception */ @SuppressWarnings("unchecked ...
- C# 导出 excel 复杂格式 html导出
/// <summary> /// 夜班津贴统计导出 /// </summary> public void ExportOtStat(string data) { var in ...
- js前端解析excel文件
使用纯Javascript解析excel文件. 使用的是开源的解析excel的js库:sheetjs.github地址:https://github.com/SheetJS/js-xlsx 首先引用J ...
- 导出excel(利用工具类导出excel)
/** * 添加导出功能 * @param creditPageResult * @param request * @param response */ @RequestMapping(value = ...
随机推荐
- NRF51822之FICR
uint32_t deviceID[2];union{ uint32_t DW; uint8_t B[4];} device_ID;//read device ID deviceID ...
- Oracle修改表或者字段的注释
转自:https://www.cnblogs.com/fx-blog/p/7132833.html 语句:comment on table 表名 is '表的注释信息'; comment on col ...
- 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 ...
- mingw 设置python 设置git环境变量
1.python路径设置: 安装python 比如目录:C:\Python27 假如mingw安装C盘根目录下的话,进入下面目录:C:\MinGW\msys\1.0\etc 找到 fstab 文件修改 ...
- 学习别人的rpc框架
https://my.oschina.net/huangyong/blog/361751 https://gitee.com/huangyong/rpc 在此文基础上的另一个实现,解决了原文中一些问题 ...
- Sonya and Exhibition 1004B
B. Sonya and Exhibition time limit per test 1 second memory limit per test 256 megabytes input stand ...
- linux内核中的const成员是否可以修改?
本文的基础知识:由于前半部分内容是转的,且不知道原文出处,没法给出原文地址,大家自行百度 const的实现机制 const究竟是如何实现的呢?对于声明为const的内置类型,例如int,short,l ...
- Spring+Quartz 实现定时任务的配置方法
Spring+Quartz 实现定时任务的配置方法 整体介绍 一.Quartz介绍 在企业应用中,我们经常会碰到时间任务调度的需求,比如每天凌晨生成前天报表,每小时生成一次汇总数据等等.Quartz是 ...
- Java如何创建参数个数不限的函数
可变的参数类型,也称为不定参数类型.英文缩写是varargus,还原一下就是variable argument type.通过它的名字可以很直接地看出来,这个方法在接收参数的时候,个数是不定的. pu ...
- spring boot 集成Thymeleaf