【问题标题】:How to add textfile download button in Javascript DataTables?如何在 Javascript DataTables 中添加文本文件下载按钮?
【发布时间】:2022-01-23 18:30:06
【问题描述】:

我需要添加一个按钮来将数据表内容下载为文本文件。我在数据表中只有一列。我的代码如下。 Copy、excel、csv、pdf 和 print 都可以在下面的代码中正常工作。

$(document).ready(function () {
         $('#dataTableExample').DataTable({
            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'copyHtml5', footer: true
                },
                {
                    extend: 'excelHtml5', footer: true
                },
                {
                    extend: 'csvHtml5', footer: true
                },
                {
                    extend: 'pdfHtml5', footer: true
                }
            ],

        });
    });

【问题讨论】:

  • 您可以在 SO 中使用code snippet 并提供一个工作示例让人们更容易理解您的问题

标签: javascript datatables export


【解决方案1】:

built-in DataTables 按钮不支持将单个列导出为纯文本文件。但是,您可以通过使用 custom action 定义自己的按钮来实现此目的。

下面的 sn-p 应该可以实现您想要的,它可以添加到设置时传递给DataTablebuttons 数组中。这将添加一个名为“TXT”的按钮,该按钮从表中的第一列获取过滤后的值,然后与 CR+LF 连接,然后触发将结果下载为 .txt 文件。

{
  text: 'TXT',
  action: function (e, dt, node, config) {
    // Generate the text to be exported
    // Please note...
    // - This only takes column 0
    // - The output is filtered based on the applied search
    // - This doesn't include the header or footer
    // - This uses CR+LF line endings
    let text = dt.columns(0, { search: 'applied' }).data().toArray()[0].join('\r\n');

    // Add an element to the page contianing the encoded txt to download
    // click the element to trigger the download, then remove the element
    let element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', 'data.txt');
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  }
}

可以在https://jsfiddle.net/a3eucptL/ 看到一个工作示例。

【讨论】:

    猜你喜欢
    • 2016-08-01
    • 2020-10-15
    • 1970-01-01
    • 2017-10-15
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多