table2excel 导出表格有边框,文字居中

2023-10-30

应项目需要,前端直接导出表格中的数据。
百度找到了table2excel ,很实用,但是导出的表格没有边框,且表格中的数据没有居中。
网上没找到对应的办法,就自己对table2excel.js做了修改,能够实现导出的表格有边框,文字居中的要求,故写本文记录下。

基于jQuery table2excel - v1.1.1,大家可根据实际需求,将功能再做升级。我现在也只是简单粗暴的添加了下功能。

修改的位置如下:
52行:head: "<table >"修改为head: "<table border='1'>"
65行:tempRows += "<tr >";修改为tempRows += "<tr align='center' valign='center' >";
75行:tempRows += "<td > </td>";修改为tempRows += "<td align='center' valign='center' > </td>";
77行:tempRows += "<td ";修改为tempRows += "<td align='center' valign='center' ";

使用的方法还是官方的方法:

 $(".table2excel").table2excel({
          exclude: ".noExl",
          name: "Excel Document Name",
          filename: "导出的文件名",
          exclude_img: true,
          exclude_links: true,
          exclude_inputs: true
      });

然后想要知道怎么解决打开表格时的不安全提示框问题。

最后附上修改后的源码,大家导入到项目中直接用就好了:

/*
 *  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
 *  
 *  添加功能:导出表格边框,文字居中
 */
//table2excel.js
;(function ( $, window, document, undefined ) {
    var pluginName = "table2excel",

    defaults = {
        exclude: ".noExl",
        name: "Table2Excel",
        filename: "table2excel",
        fileext: ".xls",
        exclude_img: true,
        exclude_links: true,
        exclude_inputs: true
    };

    // 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
            //
            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 border='1'>",//表格边框
                    tail: "</table>"
                },
                foot: "</body></html>"
            };

            e.tableRows = [];

            // get contents of table except for exclude
            $(e.element).each( function(i,o) {
                var tempRows = "";
                $(o).find("tr").not(e.settings.exclude).each(function (i,p) {

                    tempRows += "<tr align='center' valign='center' >"; //文字居中
                    $(p).find("td,th").not(e.settings.exclude).each(function (i,q) { // p did not exist, I corrected

                        var rc = {
                            rows: $(this).attr("rowspan"),
                            cols: $(this).attr("colspan"),
                            flag: $(q).find(e.settings.exclude)
                        };

                        if( rc.flag.length > 0 ) {
                            tempRows += "<td align='center' valign='center' > </td>"; // exclude it!! //文字居中
                        } else {
                            tempRows += "<td align='center' valign='center' "; //文字居中
                            if( rc.rows > 0) {
                                tempRows += " rowspan=\'" + rc.rows + "\' ";
                            }
                            if( rc.cols > 0) {
                                tempRows += " colspan=\'" + rc.cols + "\' ";
                            }
                            tempRows += "/>" + $(q).html() + "</td>";
                        }
                    });

                    tempRows += "</tr>";

                });
                // exclude img tags
                if(e.settings.exclude_img) {
                    tempRows = exclude_img(tempRows);
                }

                // exclude link tags
                if(e.settings.exclude_links) {
                    tempRows = exclude_links(tempRows);
                }

                // exclude input tags
                if(e.settings.exclude_inputs) {
                    tempRows = exclude_inputs(tempRows);
                }
                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) ) {
                 Object.keys(table).forEach(function(i){
                      //fullTemplate += e.template.sheet.head + "{worksheet" + i + "}" + e.template.sheet.tail;
                      fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;
                });
            }

            fullTemplate += e.template.mid;

            if ( $.isArray(table) ) {
                 Object.keys(table).forEach(function(i){
                    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() {
                if ( !$.data( e, "plugin_" + pluginName ) ) {
                    $.data( e, "plugin_" + pluginName, new Plugin( this, options ) );
                }
            });

        // chain jQuery functions
        return e;
    };

})( jQuery, window, document );

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

table2excel 导出表格有边框,文字居中 的相关文章

随机推荐

  • “geckodriver“ executable needs to be in PATH报错解决

    报此错误 方法如下 默认去找firefox 没有下载的可去下载火狐 1 使用pip安装selenium 默认安装最新版本 需要到官网上下载与系统相应的最新版本geckodriver https github com mozilla geck
  • [深度学习基础] 2. 线性分类器

    本文将以 softmax 线性分类器为例 讨论数据驱动过程的各组成部分 同时本章是后文非线性分类器和深度学习的铺垫 1 训练数据 给定由 m 张图像组成的训练集 每个图像的标记是 K 个不同类中的一个 其中 i 用于对训练实例进行索引 x
  • C语言系列之单词分析

    给出一个单词后 找到出现最多的字母和这 个字母出现的次数 输出两行 第一行包含一个英文字母 表示单词中出现得最多的字母是哪 个 如果有多个字母出现的次数相等 输出字典序最小的那个 第二行包含一个整数 表示出现得最多的那个字母在单词中出现的次
  • 解决Package is not available (for R ve【PACKAGE ‘XXX’ IS NOT AVAILABLE (FOR R VERSION X.Y.Z)” WARNING?】

    解决Package is not available for R version XXX PACKAGE XXX IS NOT AVAILABLE FOR R VERSION X Y Z WARNING 目录 更新R 不推荐 更改或指定镜像
  • Java中的List的容量设置

    List接口的大小为可变数组的实现 实现了所有可选列表操作 并允许包括 null 在内的所有元素 ArrayList继承于List接口 除继承过来的方法外 还提供一些方法来操作内部用来存储列表的数组的大小 每个ArrayList实例都有一个
  • 基于注意力机制的BiGRU

    http www c s a org cn html 2019 3 6816 html
  • 从零开始学Swift计时器App开发

    这款App的灵感来自于我家厨房的百利达计时器 平时我主要用它来控制烹饪的时间和实践番茄工作法 它的操作很简单 点击复位可以对时间清零 点击秒 1分 3分 5分可以不断增加倒计时时间 点击 开始 停止 来启动或停止倒计时 通过此教程 你将学习
  • 最长回文数

    给你一个字符串 s 找到 s 中最长的回文子串 示例 1 输入 s babad 输出 bab 解释 aba 同样是符合题意的答案 把每个字符都当作回文数的中心向两边查找 注意也要区分回文的中心是一位数还是两位数 时间复杂度 O n var
  • LSTM预测实例(数据集展示)

    数据集展示 load and plot dataset from pandas import read csv from pandas import datetime from matplotlib import pyplot 加载数据 d
  • uniapp小程序中input内容选中效果

    先看下效果 点击按钮选中input的内容 使用 focus 配合 selection start和selection end实现 html
  • 【Unity3D】代码移动动画优化

    设置X轴和Y轴的动画曲线 通过AnimationCurve Evaluate获取进度中X和Y移动的进度的值 控制偏移 可以根据动画曲线控制平移时候的效果 using LuaInterface using System Collections
  • 论文笔记(1)DenseBox: Unifying Landmark Localization with End to End Object Detection

    本文的贡献有一下几点 1 实现了end to end的学习 同时完成了对bounding box和物体类别的预测 2 在多任务学习中融入定位信息 提高了检测的准确率 我们先来看看他和其他几篇代表性文章之间的不同 在OverFeat 1 中提
  • 机器学习方法(四):决策树Decision Tree原理与实现技巧

    欢迎转载 转载请注明 本文出自Bin的专栏blog csdn net xbinworld 技术交流QQ群 433250724 欢迎对算法 技术 应用感兴趣的同学加入 前面三篇写了线性回归 lasso 和LARS的一些内容 这篇写一下决策树这
  • DVWA 通关笔记:JavaScript Attacks

    概述 什么是JavaScript Attack JavaScript Attack即JS攻击 攻击者可以利用JavaScript实施攻击 通关要求 提交 success 一词即可获胜 下面我们分别对Low 低级 Medium 中级 High
  • java流程控制语句

    流程控制语句 一 分支语句 1 1 流程控制语句分类 1 2 if语句 1 3 switch语句 二 循环语句 2 1 for循环语句 2 2 while循环语句 2 3 do while循环语句基本格式 2 4 三种循环的区别 2 5 跳
  • 一种基于深度学习的单导联心电信号睡眠呼吸暂停检测方法

    在R峰识别的基础上 加入S峰的识别 并论正了该策略对检测结果的有效性 1 大致方法 将数据集 ECG信号 划分为每五分钟的一个片段 为了减少噪声和信号伪影 首先对信号应用了一个有限脉冲响应 FIR 带通滤波器 使用保持8 12Hz的带通滤波
  • 【Lingo 18.0及其安装教程】

    Lingo 18 0及其安装教程 Lingo是Linear Interactive and General Optimizer的缩写 即 交互式的线性和通用优化求解器 由美国LINDO系统公司 Lindo System Inc 推出的 可以
  • 小程序使用变量的值作为变量使用

    使用同一个日期选择组件 给不同的日期选择框赋值 发现想动态的给不同的组件赋值 这时候需要根据变量中暂存的组件变量赋值 这里做一下记录 calendarSelect event this setData calendarVisable fal
  • Linux常用命令-文件操作 网络命令 性能命令

    1 1文件操作命令 改变目录 cd 查看当前路径 pwd 创建目录 mkdir tmp test 创建文件 touch tmp a txt 删除文件或文件夹 rm tmp a txt 删除文件 rm r tmp test 删除文件夹 复制文
  • table2excel 导出表格有边框,文字居中

    应项目需要 前端直接导出表格中的数据 百度找到了table2excel 很实用 但是导出的表格没有边框 且表格中的数据没有居中 网上没找到对应的办法 就自己对table2excel js做了修改 能够实现导出的表格有边框 文字居中的要求 故