从数据表中导出选定行的 CSV 文件

export csv file for selected rows from datatable

本文关键字:CSV 文件 数据表      更新时间:2023-09-26

我使用以下示例创建了一个数据表:

1.单列搜索

2.文件导出

我的代码如下:

 <script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );
    // DataTable
    var table = $('#example').DataTable({'scrollX':true, 'dom': 'lBfrtip','buttons': ['csv']});
    // Apply the search
    table.columns().every( function () {
        var that = this;
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );
</script>

这段代码运行良好。现在,我只想导出选定的行,而不更改示例 1 中的数据表结构。我不是Jquery的专家。那么任何人都可以帮助我吗?也可以添加用于选择行的复选框吗?

谢谢

我使用以下代码设法做到这一点:

    <script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );
    // DataTable
    var table = $('#example').DataTable({'scrollX':true, 'dom': 'lBfrtip',buttons: [{ extend: 'csv',text: 'CSV all'},{extend: 'csv',text: 'CSV selected',exportOptions: {modifier: {selected: true}}}],select: true});
    // Apply the search
    table.columns().every( function () {
        var that = this;
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );
</script>

所以我在现有脚本中添加了新代码。

buttons: [{ extend: 'csv',text: 'CSV all'},{extend: 'csv',text: 'CSV selected',exportOptions: {modifier: {selected: true}}}],select: true