数据表删除导出到 pdf 和 excel 时的列

2024-03-16

我在导出到 pdf、excel 之前删除列时遇到问题。 第二个问题是由于该列,该列的反向部分无法正常工作 这是我使用的代码

$(document).ready(function(){
            var arrayCol = new Array();
            var table = $('#example').DataTable({
                dom: 'B<"top"iflp<"clear">>rt<"bottom"ip<"clear">>',
                initComplete:function (  ) {
                    var len = this.api().columns().count();
                    var array =  Array.from(Array(len).keys());
                    arrayCol = array.reverse();
                  },
            buttons: [
      { 
        extend: 'pdf',
        text: 'To PDF',
        exportOptions: {
          rows: function ( idx, data, node ) {
            return data.reverse();
          },
          format: {
          columns: ':visible:not(.not-export-col)', 
            header: function ( data, idx, node ) {
              var headers = $('#example').DataTable().table().header();
              var reversedHeaders = headers.innerText.split('\t').reverse();
              return reversedHeaders[idx];
            }
          }
        }
      },
               { 
        extend: 'excel',
        text: 'exel',
        exportOptions: {
        columns: ':visible:not(.not-export-col)', 
          rows: function ( idx, data, node ) {
            return data.reverse();
          },
          format: {
            header: function ( data, idx, node ) {
              var headers = $('#example').DataTable().table().header();
              var reversedHeaders = headers.innerText.split('\t').reverse();
              return reversedHeaders[idx];
            }
          }
        }
      }
    ]
                });
        });

and here https://jsfiddle.net/xekv5Lwh/4/是活生生的例子


您可以扩展所使用的方法here https://stackoverflow.com/a/68885988/12567365处理抑制您不想导出的一列或多列的额外要求。

您对列选择器的使用效果很好:

columns: ':visible:not(.not-export-col)

为了构建我们想要导出的标头列表,initComplete可以使用函数(因此我们只执行此过程一次)。

我们还可以使用initComplete函数来构建我们所做的列索引数组not想要导出:

var ignorePositions = []; // column indexes of data NOT to be exported
var reversedHeaders = []; // with "not-export" headings removed

功能:

initComplete:function (  ) {
  var thead = $( '#example' ).DataTable().table().header();
  var tds = $( thead ).find( 'th' ).each(function( index ) {
    if ( ! $( this ).hasClass('not-export-col') ) {
      reversedHeaders.push( $( this ).text() );
    } else {
      ignorePositions.push(index);
    }
  });
  reversedHeaders.reverse(); // to give us the export order we want
  ignorePositions.reverse(); // reversed for when we splice() - see below
}

上面的代码填充了两个数组:

  • reversedHeaders- 包含我们将导出的那些列的标题列表(反向)。
  • ignorePositions- 包含要忽略的列索引列表。在我们的示例中,唯一这样的列是最后一列(索引 6)。

然后我们就可以在我们修改后的数组中使用上面的数组了exportOptions code:

exportOptions: {
  rows: function ( idx, data, node ) {
    var keepRowData = [];
    // we splice to remove those data fields we do not want to export:
    ignorePositions.forEach(idx => data.splice(idx, 1) );
      return data.reverse();
  },
  columns: ':visible:not(.not-export-col)',
  format: { 
    header: function ( data, idx, node ) {
      return reversedHeaders[idx];
    }
  }
}

唯一棘手的部分是需要使用splice直接修改原来的data大批。这会从原始数据数组中删除每个不需要的元素,而不创建新的数据数组。

把它们放在一起:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
  <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
  <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">

  <!-- buttons -->
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.5/css/buttons.dataTables.min.css"/> 
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.5/js/dataTables.buttons.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.5/js/buttons.colVis.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.5/js/buttons.flash.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.5/js/buttons.html5.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.5/js/buttons.print.min.js"></script>

</head>

<body>

<div class="container">
      <table id="example" class="display nowrap" width="100%">
        <thead>
          <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
            <th class="not-export-col">opr</th>
          </tr>
        </thead>
<!--
        <tfoot>
          <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
            <th class="not-export-col">opr</th>
          </tr>
        </tfoot>
-->
        <tbody>
          <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$3,120</td>
            <td><a href="www.google.com"><i class="wb-edit"></i></a></td>
          </tr>
<!--
          <tr>
            <td>Garrett Winters</td>
            <td>Director</td>
            <td>Edinburgh</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$5,300</td>
            <td><a href="www.google.com"><span class="iconify" data-icon="fa:edit"></span></a></td>
          </tr>
          <tr>
            <td>Ashton Cox</td>
            <td>Technical Author</td>
            <td>San Francisco</td>
            <td>66</td>
            <td>2009/01/12</td>
            <td>$4,800</td>
            <td><a href="www.google.com"><span class="iconify" data-icon="fa:edit"></span></a></td>
          </tr>
          <tr>
            <td>Cedric Kelly</td>
            <td>Javascript Developer</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>2012/03/29</td>
            <td>$3,600</td>
            <td><a href="www.google.com"><span class="iconify" data-icon="fa:edit"></span></a></td>
          </tr>
          <tr>
            <td>Jenna Elliott</td>
            <td>Financial Controller</td>
            <td>Edinburgh</td>
            <td>33</td>
            <td>2008/11/28</td>
            <td>$5,300</td>
            <td><a href="www.google.com"><span class="iconify" data-icon="fa:edit"></span></a></td>
          </tr>
          <tr>
            <td>Donna Snider</td>
            <td>System Architect</td>
            <td>New York</td>
            <td>27</td>
            <td>2011/01/25</td>
            <td>$3,120</td>
            <td><a href="www.google.com"><span class="iconify" data-icon="fa:edit"></span></a></td>
          </tr>
-->
        </tbody>
      </table>
    </div>
<script>

$(document).ready(function() {
  var ignorePositions = []; // column indexes of data NOT to be exported
  var reversedHeaders = []; // with "not-export" headings removed

  var table = $('#example').DataTable( {
    dom: 'B<"top"iflp<"clear">>rt<"bottom"ip<"clear">>',
    initComplete:function (  ) {
      var thead = $( '#example' ).DataTable().table().header();
      var tds = $( thead ).find( 'th' ).each(function( index ) {
        if ( ! $( this ).hasClass('not-export-col') ) {
          reversedHeaders.push( $( this ).text() );
        } else {
          ignorePositions.push(index);
        }
      });
      reversedHeaders.reverse(); // to give us the export order we want
      ignorePositions.reverse(); // reversed for when we splice() - see below
    },
    buttons: [
      { 
        extend: 'pdf',
        text: 'To PDF',
        exportOptions: {
          rows: function ( idx, data, node ) {
            var keepRowData = [];
            // we splice to remove those data fields we do not want to export:
            ignorePositions.forEach(idx => data.splice(idx, 1) );
            return data.reverse();
          },
          columns: ':visible:not(.not-export-col)',
          format: { 
            header: function ( data, idx, node ) {
              return reversedHeaders[idx];
            }
          }
        }
      }
    ]
  } );
} );

</script>

</body>
</html>

The table data, which looks like thisenter image description here:

导出为 PDF 格式如下:


最后注意事项:

  1. 我在上面的代码中只实现了PDF按钮。还需要添加 Excel 按钮代码,但应该相同。

  2. 我注释掉了<tfoot>我的代码中 HTML 表的部分。我认为这意味着您还需要添加footer: function() { ... }到您的实施,以匹配header: function() { ... }代码。我假设如下(但我没有测试这一点):

format: { 
  header: function ( data, idx, node ) {
    return reversedHeaders[idx];
  },
  footer: function ( data, idx, node ) {
    return reversedHeaders[idx];
  }
}

Update

我看到烦人的警报。这是由我的代码引起的,它改变了数据行的长度(当它拼接出一个元素时)。

第二个问题是,一旦行被反转,它就会保持反转状态 - 因此,在下次导出时,导出的数据的顺序是错误的。

要解决这两个问题是很混乱的,我提出的解决方案是有限的:

我的解决方案假设您只想隐藏最后一列.

它还依赖于您能够检测行何时被反转 - 在我的例子中,这是通过检查行数据的最终位置中的特定值来完成的 - 同样,这不是一个非常可靠的方法 - 但它是唯一的方法我现在能想到的方法。

这是更新后的代码:

$(document).ready(function() {
  var exportPositions = []; // column indexes of data NOT to be exported
  var ignorePositions = []; // column indexes of data NOT to be exported
  var reversedHeaders = []; // with "not-export" headings removed

  var table = $('#example').DataTable( {
    dom: 'B<"top"iflp<"clear">>rt<"bottom"ip<"clear">>',
    initComplete:function (  ) {
      var thead = $( '#example' ).DataTable().table().header();
      var tds = $( thead ).find( 'th' ).each(function( index ) {
        if ( ! $( this ).hasClass('not-export-col') ) {
          reversedHeaders.push( $( this ).text() );
          exportPositions.push(index);
        } else {
          ignorePositions.push(index);
        }
      });
      reversedHeaders.reverse(); // to give us the export order we want
      reversedHeaders.push('');
      ignorePositions.reverse(); // reversed for when we splice() - see below
    },
    buttons: [
      { 
        extend: 'pdf',
        text: 'To PDF',
        exportOptions: {
          rows: function ( idx, data, node ) {
            if (data[data.length - 1] === '~') {
              data.reverse(); // un-reverse an already reversed record
              data.push(data.splice(0, 1)[0]); // move first element to end of the array
            }
            // we splice to remove those data fields we do not want to export:
            ignorePositions.forEach(idx => {
              data.splice(idx, 1);
            } );
            data.reverse();
            ignorePositions.forEach(idx => {
              data.push('~'); // pad the array back to its original length
            } );
            return data;
          },
          columns: exportPositions, // here we use the array we built earlier
          format: { 
            header: function ( data, idx, node ) {
              return reversedHeaders[idx];
            }
          }
        }
      }
    ]
  } );
} );

如果您的实际实现需要隐藏多个列,那么这种方法可能不适合您。如果我对更强大的解决方案有任何想法,我会更新答案。

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

数据表删除导出到 pdf 和 excel 时的列 的相关文章

  • 仅当现有填充颜色为特定值时才填充 SVG

    我正在使用此代码来更改 SVG 对象的填充颜色 它可以工作 function g mouseenter function path rect circle this attr fill 00C8C8 但是 我只想在现有填充颜色具有特定值时更
  • Android 上的 Chrome 强制隐藏地址栏

    我最近开发了一个获取混合 http https 内容的网站 因此 我总是将地址栏显示在顶部 它不会像其他网站那样自动隐藏 这就是我要说的 This https planetkde org 是网站的链接 内容是从各种来源获取的 因此无法过滤非
  • History.pushState和页面刷新

    我开始研究 HTML5 新历史 API 不过 我有一个问题 如何处理页面刷新 例如 用户单击一个链接 该链接由 js 函数处理 该函数 异步加载页面内容 使用history pushState 更改URL 用户刷新页面 但是服务器上当然不存
  • 单击时阻止 jquery TABS 跳跃/向上滚动?

    我使用的引擎调用 jquery tabs js 脚本来处理选项卡功能 问题是 只要选项卡位于页面顶部并且您单击链接 它们就会快速向下滚动到页面底部 我已经尝试解决这个问题几个小时了 所有解决方案都指向类似的答案 但没有一个对我有用 fn t
  • 无法让 CloudKit 进行身份验证(使用 Javascript 和服务器到服务器密钥)

    我正在尝试使用苹果的cloudkit js文件以建立与 CloudKit 的服务器到服务器连接 然而 尽管配置混乱了几个小时 我似乎无法让 CloudKit 认为我的请求有效 我的配置逻辑非常简单 const privateKeyFile
  • 为什么有人将(Apache mod_expires 参数)ExpiresByType 设置为“访问加 0 秒”?

    在审查答案时这个帖子 https stackoverflow com questions 9933012 how to use mod headers and mod expires to cache 我不明白为什么这里使用 0 秒作为最佳
  • 在 JavaScript 中引用 C# 变量

    我已经阅读了很多线程 但我不明白为什么这不起作用 我正在创建一个将用作导航栏的 SharePoint Web 部件 一切都很顺利 直到我尝试在 JS 代码中引用 C 变量 这是来自 VisualWebPart1UserControl asc
  • 在 Typescript 中从基类创建子类的新实例[重复]

    这个问题在这里已经有答案了 我想创建新实例Child班级来自Base类方法 这有点复杂 但我会尽力解释 这是一个例子 class Base constructor clone Here i want to create new instan
  • JQuery - 如何检测给定 div 中存在给定类的 div 数量?

    我有一个这样的div div class x div 并包含在这个 div 中 我有几个像这样的 div div class y div div class y div div class y div etc 问题1 如何检测容器 div
  • 将 DIV 转换为单击并拖动视口

    有人知道一种不显眼的 基于原型或无框架的方法将具有大内容 例如地图 的 DIV 转换为具有固定尺寸的可点击和可拖动的 地图 容器 非常像 Google 地图 我想在大型输入表单中显示 HTML 块 这些块可能会超出可用空间 每个块可以有大约
  • XMLHttpRequest、jQuery.ajax、jQuery.post、jQuery.get 之间有什么区别

    我如何找出最适合某种情况的方法 有人可以提供一些例子来了解功能和性能方面的差异吗 XMLHttpRequest是原始浏览器对象 jQuery 将其包装成更可用和简化的形式以及跨浏览器一致的功能 jQuery ajax是 jQuery 中的通
  • 什么是闭包编译器?

    如果您不知道我在说什么 请查看以下内容 http closure compiler appspot com home http closure compiler appspot com home 这是一个 JavaScript 压缩器 在他
  • 如何使表格单元格的最小宽度为 3 位数字?

    如何使表格中的每个单元格的最小宽度为 3 位数字且不会更大 现在我正在硬编码min width 但我不喜欢硬编码一个值 因为我将来可能想更改字体 如果需要Javascript也没关系 table border 1 tr td 1 td td
  • 防止 Bootstrap IE 下拉列表在滚动条单击时关闭

    在 IE 中 单击下拉菜单滚动条时 下拉菜单将关闭 当您使用鼠标滚轮滚动它时 效果很好 这是代码层链接 https www codeply com go Uh8qadr3q2 https www codeply com go Uh8qadr
  • jQuery clone() 复制数据...有时...?

    使用下面的示例 我有一个tr我正在复制 它包含一个 jQueryautocomplete 第一次克隆时 自动完成功能不起作用 因为附加的data items 一片空白 第二次单击 添加 按钮时 自动完成功能将起作用 此后 再次单击 添加 会
  • 让管道自我刷新角度

    我有来自后端的静态时间戳 我想每 1 秒刷新一次管道以获取现在的日期 这是我的烟斗 import Pipe PipeTransform from angular core import moment from moment Pipe nam
  • TinyMCE:将 CSS 类属性与 formatselect-dropdown 格式结合使用

    我想定制格式 http wiki moxiecode com index php TinyMCE Configuration theme advanced blockformats在 TinyMCE 中格式选择下拉菜单 http wiki
  • RemoveEventListener 在 Firefox 版本 58 中不起作用

    但它在 Chrome 中有效 这是我的 UI EventBus 代码 原型 addEventListener方法是一样的 只不过remove换成了add UI EventBus removeEventListener function ob
  • 在javascript中我们如何识别一个对象是Hash还是Array?

    我的 JSON 调用的输出可以是数组或哈希 我如何区分这两者 现代浏览器支持Array isArray obj method See MDN https developer mozilla org en US docs Web JavaSc
  • IE 中带有“删除”方法的 jQuery.ajax 问题

    我有一个页面 用户可以使用按钮编辑各种内容并选择触发 ajax 调用 特别是 一个操作会导致远程调用一个 url 其中包含一些数据和 放置 请求 这 因为我使用的是宁静的 Rails 后端 会触发我的更新操作 我还有一个删除按钮 它调用相同

随机推荐

  • 将聊天服务器实现为 WebService

    我有一个学校项目 我必须在其中实现一个聊天应用程序 其服务器将是一个 java web 服务 问题是 我一直认为 Web 服务是调用远程功能的一种方式 而且我不知道如何在 Web 服务上保持 会话 活动 也不知道如何跟踪当前处于活动状态的所
  • 在 URL 中发送参数的最佳且安全的方法

    我正在开发一个网站 该网站具有根据 id 更新和删除数据的功能 现在我担心的是我的网址是 www example com public controller action 1 如果行动是delete 任何人都可以change id from
  • 如何处理 Nimbus Look and Feel 中的派生颜色?

    我想要的是使不可编辑的文本区域的背景与其禁用的背景相同 我知道该颜色可以从UIManager用钥匙TextArea disabled DerivedColor color 214 217 223 parent control offsets
  • 是否可以使用引用键在 Rmarkdown 文档中间插入文章的完整参考文献?

    Here http rmarkdown rstudio com authoring bibliographies and citations html我学习如何在文本中间插入引文并在文档末尾生成完整的参考书目 我想知道是否可以使用引用键得到
  • iText 中的 PdfPageEventHelper

    我正在创建一个 pdf 其中每个 pdf 页面的标题将根据当前页码进行自定义 例如 在第一页中 标题是 第一页 在第二页中 标题是 第二页 依此类推 我们现在要做的是将标题添加到 PdfPTable 中 然后我们还将许多其他内容添加到 Pd
  • UIAlertView按钮操作代码

    有谁知道如何对按钮进行操作UIAlertview 如果是这样 请指导我 void alertView UIAlertView alertView didDismissWithButtonIndex NSInteger buttonIndex
  • iframe加载时间限制使用javascript

    我需要在 5000 毫秒后停止加载我的 iframe 页面 我正在使用这些 但它每 5000 毫秒刷新一次 iframe 这是什么问题 请修复它 谢谢
  • PendingIntent 上的“requestCode”有何用途?

    背景 我通过 AlarmManager 使用 PendingIntent 来发出警报 问题 起初我认为为了取消以前的请求 我必须提供我之前用来启动警报的确切请求代码 但后来我发现我错了 因为取消API http developer andr
  • 如何将 pandas 安装到 Visual Studio Code 中?

    我想读取 Excel CSV 文件 经过研究 我意识到我需要import pandas as pd 有没有办法将其安装到 Visual Studio Code 中 我试过打字import pandas as pd 但显示一条红线 我对Pyt
  • 尝试显示位图时,一目了然的应用程序小部件图像崩溃

    当我尝试在应用程序中显示位图图像 我的应用程序图标 时 它工作正常 但当我尝试在 Widget Glance 中显示它时崩溃 这是我的位图代码 val icon packageManager getApplicationIcon com m
  • az devops 登录挂起

    我正在使用 Windows 10 Azure PowerShell Az 模块 DevOps 扩展 0 18 0 我已登录 DevOps 实例并能够运行所有相关命令 现在 我需要登录到不同的组织 项目 每次执行登录子命令时 窗口都会挂起并锁
  • 将两个表中的数据放入一个视图中

    是否可以将两个表 具有相同字段 的数据抓取到一个视图中 基本上 视图将数据视为一张表 是的 使用 UNION CREATE VIEW vw combined AS SELECT FROM TABLE1 UNION ALL SELECT FR
  • SpringBoot 与 Jakarta Validation Api 未使用 @Valid Annotation 进行验证

    我对 Spring boot 和依赖项 jakarta validation api 有疑问 实际上我有一个简单的 DTO 其中包含一些属性 但是当我在 Valid 注释中调用 REST 函数时 此属性并未得到验证 有人能发现我的错误吗 我
  • 在Python中初始化对象列表

    我希望初始化一个不为空的对象数组 列表 类构造函数生成数据 在 C 和 Java 中我会做这样的事情 Object lst new Object 100 我已经查过了 但是有没有一种Python式的方法来完成这个任务 这并不像我想象的那样工
  • 如何在android的非活动类中实现类似“完成”的功能?

    此对话框询问您是否要安装其他应用程序 因此 当单击无按钮时 它必须返回到上一个屏幕 downloadDialog setNegativeButton stringButtonNo new DialogInterface OnClickLis
  • DynamicLINQ - 在字符串内转义双引号

    我正在尝试使用动态过滤系统动态LINQ图书馆 当您执行以下操作时 我一切都会顺利进行 查找名字是鲍勃的人 Context Users Where FirstName Bob 但当我想做的时候遇到了问题 查找名字为 Bob 的人 其中 Bob
  • 如何使用c#在DataGrid(WPF)中显示列表列表

    我有一个标题列表 列 然后是数据行 并希望通过两种方式绑定在 DataGrid 中显示它 List
  • 强制 UIImagePickerController 裁剪方形图像

    我们如何强制 UIImagePickerController 裁剪方形图像 我到处寻找 但没有找到可靠的解决方案 谢谢 var imagePickerController UIImagePickerController UIImagePic
  • 为什么 char 数组必须以空字符结尾?

    为什么 chararray必须以空字符结尾 有什么理由我必须将空字符添加到每个char array 看来他们受到的待遇是一样的 char 数组不必以 null 终止 不依赖于此的标准库函数包括memcpy memmove strncpy 最
  • 数据表删除导出到 pdf 和 excel 时的列

    我在导出到 pdf excel 之前删除列时遇到问题 第二个问题是由于该列 该列的反向部分无法正常工作 这是我使用的代码 document ready function var arrayCol new Array var table ex