使用服务器端处理从DataTables导出所有内容?

Mik*_*ike 6 javascript php jquery datatables-1.10

我有使用DataTables服务器端处理的表格在我的网站上显示.我希望能够"全部导出"并导出所有行,而不仅仅是要显示的行.有60000多行和65+列,因此必须使用服务器端处理.

我尝试过一些东西,但到目前为止还没有任何效果.

我试过这个:

{ extend: 'excel',
    text: 'Export Current Page',
    exportOptions: {
        modifier: {
            page: 'current'
        }
    },
    customize: function (xlsx)
    {
        var sheet = xlsx.xl.worksheets['sheet1.xml'];
        $('row:first c', sheet).attr('s', '7');
    }
}
Run Code Online (Sandbox Code Playgroud)

其中只导出了页面上显示的行.

我试过这个:

{
    text: 'Export All to Excel',
    action: function (e, dt, button, config)
    {
        dt.one('preXhr', function (e, s, data)
        {
            data.length = -1;
        }).one('draw', function (e, settings, json, xhr)
        {
            var excelButtonConfig = $.fn.DataTable.ext.buttons.excelHtml5;
            var addOptions = { exportOptions: { 'columns': ':all'} };

            $.extend(true, excelButtonConfig, addOptions);
            excelButtonConfig.action(e, dt, button, excelButtonConfig);
        }).draw();
    }
}
Run Code Online (Sandbox Code Playgroud)

这会将整个表的数据发送到屏幕,而不是使用分页并将整个数据集发送到excel文件.

我在Google上搜索过这里,但是没有找到可行的解决方案.

我还要提一下,我想根据表中设置的当前过滤器导出全部.这样最终用户只能获得他们正在搜索的行的导出.它们通常将其限制为30k-40k行,仍然使用65+列.我(还)不允许删除/隐藏列.

编辑/ UPDATE

这是次要考虑因素:如果我无法从服务器的响应中导出全部,我可以在服务器上构建Excel文件吗?我的服务器没有安装Excel,我仍然希望我的最终用户获取该文件.我确信我必须找到一种方法将Excel放到我的服务器上,但是如何将任何创建的文件传输给最终用户,这甚至比仅发送一个包含整个数据集的响应更快用户计算机上的Excel文件?

编辑

我建议尝试使用jquery $.ajax()来实现这个功能.如果有人可以告诉我如何做到这一点,我会尝试第三个按钮.

我已经可以使用用户添加的相同过滤器和排序来提取所有数据,并使用按钮执行此操作.上面的第二次尝试确实如此,但将其发送到屏幕.我有PHPExcel和一个可以创建Excel工作表的文件.我如何获取第二个按钮并将其发送到另一个文件以创建Excel工作表?我认为使用jquery $.ajax()可能会起作用,我只是不知道如何使用它.我知道我必须使用,$_POST因为数据可能太大而无法用于$_GET将数据发送到PHPExcel文件.

我已经可以导出为CSV,但我需要使用CSV没有的格式导出.这就是为什么我要使用PHPExcel的麻烦.

编辑III

我正在尝试这个,虽然它还没有工作:

{
    text: 'Export all to Excel II',
    action: function (e, dt, button, config)
    {
        dt.one('preXhr', function (e, s, data)
        {
            data.length = -1;
        }).one('export', function (e, settings, json, xhr)
        {
            var excelButtonConfig = $.fn.DataTable.ext.buttons.excelHtml5;
            var addOptions = { exportOptions: { 'columns': ':all'} };

            $.extend(true, excelButtonConfig, addOptions);
            excelButtonConfig.action(e, dt, button, excelButtonConfig);
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑4

希望最后编辑.

我知道我必须做三件事来完成这项工作:

  1. 获取当前的排序和筛选
  2. 获取长度设置为-1的数据集
  3. 发送到PHPExcel文件以处理和创建Excel文件我可以创建一个这样的按钮:

    {text:'将所有数据导出到Excel',操作:}

我只是不知道需要采取什么行动.

我上面的第二次尝试拉出了我需要的整个数据集,但将其发送到屏幕而不是我的PHPExcel文件(ExportAllToExcel.php).

我一直试图解决这个问题,并没有走得太远.我被告知我需要使用$.ajax()这个,我被告知我不需要使用它.我曾经尝试过,有过没有,无法到达任何地方.

我也尝试使用它没有效果:

$.fn.dataTable.ext.buttons.export =
{
    className: 'buttons-alert',
    "text": "Export All Test",
    action: function (e, dt, node, config)
    {
        var SearchData = dt.search();
        var OrderData = dt.order();
        alert("Test Data for Searching: " + SearchData);
        alert("Test Data for Ordering: " + OrderData);
    }
};
Run Code Online (Sandbox Code Playgroud)

Al *_*uin 5

First add the follwoing code in DataTable

"dom": 'Blfrtip',
                    "buttons": [
                        {
                            "extend": 'excel',
                            "text": '<button class="btn"><i class="fa fa-file-excel-o" style="color: green;"></i>  Excel</button>',
                            "titleAttr": 'Excel',
                            "action": newexportaction
                        },
                    ],
Run Code Online (Sandbox Code Playgroud)

Then add this function inside $(document).ready() function

function newexportaction(e, dt, button, config) {
         var self = this;
         var oldStart = dt.settings()[0]._iDisplayStart;
         dt.one('preXhr', function (e, s, data) {
             // Just this once, load all data from the server...
             data.start = 0;
             data.length = 2147483647;
             dt.one('preDraw', function (e, settings) {
                 // Call the original action function
                 if (button[0].className.indexOf('buttons-copy') >= 0) {
                     $.fn.dataTable.ext.buttons.copyHtml5.action.call(self, e, dt, button, config);
                 } else if (button[0].className.indexOf('buttons-excel') >= 0) {
                     $.fn.dataTable.ext.buttons.excelHtml5.available(dt, config) ?
                         $.fn.dataTable.ext.buttons.excelHtml5.action.call(self, e, dt, button, config) :
                         $.fn.dataTable.ext.buttons.excelFlash.action.call(self, e, dt, button, config);
                 } else if (button[0].className.indexOf('buttons-csv') >= 0) {
                     $.fn.dataTable.ext.buttons.csvHtml5.available(dt, config) ?
                         $.fn.dataTable.ext.buttons.csvHtml5.action.call(self, e, dt, button, config) :
                         $.fn.dataTable.ext.buttons.csvFlash.action.call(self, e, dt, button, config);
                 } else if (button[0].className.indexOf('buttons-pdf') >= 0) {
                     $.fn.dataTable.ext.buttons.pdfHtml5.available(dt, config) ?
                         $.fn.dataTable.ext.buttons.pdfHtml5.action.call(self, e, dt, button, config) :
                         $.fn.dataTable.ext.buttons.pdfFlash.action.call(self, e, dt, button, config);
                 } else if (button[0].className.indexOf('buttons-print') >= 0) {
                     $.fn.dataTable.ext.buttons.print.action(e, dt, button, config);
                 }
                 dt.one('preXhr', function (e, s, data) {
                     // DataTables thinks the first item displayed is index 0, but we're not drawing that.
                     // Set the property to what it was before exporting.
                     settings._iDisplayStart = oldStart;
                     data.start = oldStart;
                 });
                 // Reload the grid with the original page. Otherwise, API functions like table.cell(this) don't work properly.
                 setTimeout(dt.ajax.reload, 0);
                 // Prevent rendering of the full data to the DOM
                 return false;
             });
         });
         // Requery the server with the new one-time export settings
         dt.ajax.reload();
     }
Run Code Online (Sandbox Code Playgroud)


Mik*_*ike 3

我主要有这个工作。现在已经超时,但由于数据大小而不是此工作,这是一个单独的问题。对于小型数据集,它的效果非常好。

这就是我创建按钮的方式(这是我在这里使用的导出按钮):

"buttons": [{
                extend: 'collection',
                text: 'Selection',
                buttons: ['selectAll', 'selectNone']
            }, {
                extend: 'collection',
                text: 'Export',
                buttons: ['export', 'excel', 'csv', 'pdf', { extend: 'excel',
                    text: 'Export Current Page',
                    exportOptions: {
                        modifier: {
                            page: 'current'
                        }
                    },
                    customize: function (xlsx)
                    {
                        var sheet = xlsx.xl.worksheets['sheet1.xml'];
                        $('row:first c', sheet).attr('s', '7');
                    }
                }]
            }
            ]
Run Code Online (Sandbox Code Playgroud)

这是上面创建的按钮的初始化:

$.fn.dataTable.ext.buttons.export =
{
    className: 'buttons-alert',
    id: 'ExportButton',
    text: "Export All Test III",
    action: function (e, dt, node, config)
    {
        var SearchData = dt.rows({ filter: 'applied' }).data();
        var SearchData1 = dt.search();
        console.log(SearchData);
        var OrderData = dt.order();
        console.log(SearchData1);
        var NumCol = SearchData[0].length;
        var NumRow = SearchData.length;
        var SearchData2 = [];
        for (j = 0; j < NumRow; j++)
        {
            var NewSearchData = SearchData[j];
            for (i = 0; i < NewSearchData.length; i++)
            {
                NewSearchData[i] = NewSearchData[i].replace("<div class='Scrollable'>", "");
                NewSearchData[i] = NewSearchData[i].replace("</div>", "");
            }
            SearchData2.push([NewSearchData]);
        }

        for (i = 0; i < SearchData2.length; i++)
        {
            for (j = 0; j < SearchData2[i].length; j++)
            {
                SearchData2[i][j] = SearchData2[i][j].join('::');
            }
        }
        SearchData2 = SearchData2.join("%%");
        window.location.href = './ServerSide.php?ExportToExcel=Yes';
    }
};
Run Code Online (Sandbox Code Playgroud)

这是ServerSide.php文件中获取数据并将其发送到服务器进行处理的部分:

require('FilterSort.class.php');

if (isset($_GET['ExportToExcel']) && $_GET['ExportToExcel'] == 'Yes')
{
    $request = @unserialize($_COOKIE['KeepPost']);
    $DataReturn = json_encode(FilterSort::complex($request,$sqlConnect,$table,$primaryKey,$ColumnHeader));
    require './ExportAllToExcel.php';
}
else
{
    echo json_encode(FilterSort::complex($request,$sqlConnect,$table,$primaryKey,$ColumnHeader));
}
Run Code Online (Sandbox Code Playgroud)

这是我设置用于保存搜索和排序条件的 cookie 的方法:

if(isset($_POST['draw']))
{
    $KeepPost = $_POST;    
    $KeepPost['length'] = -1;
    $PostKept = serialize($KeepPost);
    setcookie("KeepPost",$PostKept,time() + (60*60*24*7));
}
Run Code Online (Sandbox Code Playgroud)

所有这些组合将正确的条件发送到FilterSort.class.php,后者应处理条件并将数据集返回到ExportAllToExcell.php,然后创建 Excel 文件。现在我正在向它发送大量报告,但它超时了。

更新

我稍微改变了我这样做的方式:

这是一组新按钮:

"buttons": [{
    extend: 'collection',
    text: 'Export',
    buttons: ['export', { extend: 'csv',
        text: 'Export All To CSV',              //Export all to CSV file
        action: function (e, dt, node, config)
        {
            window.location.href = './ServerSide.php?ExportToCSV=Yes';
        }
    }, 'csv', 'pdf', { extend: 'excel',
        text: 'Export Current Page',            //Export to Excel only the current page and highlight the first row as headers
        exportOptions: {
            modifier: {
                page: 'current'
            }
        },
        customize: function (xlsx)
        {
            var sheet = xlsx.xl.worksheets['sheet1.xml'];
            $('row:first c', sheet).attr('s', '7');
        }
    }]
}
]
Run Code Online (Sandbox Code Playgroud)

以下是创建“全部导出到 Excel”按钮的方法:

$.fn.dataTable.ext.buttons.export =
{
    className: 'buttons-alert',                         //Adds the "Export all to Excel" button
    id: 'ExportButton',
    text: "Export All To Excel",
    action: function (e, dt, node, config)
    {
        window.location.href = './ServerSide.php?ExportToExcel=Yes';
    }
};
Run Code Online (Sandbox Code Playgroud)

这些现在将数据发送到我之前使用的相同ServerSide.php文件:

require('FilterSort.class.php');
if (isset($_GET['ExportToExcel']) && $_GET['ExportToExcel'] == 'Yes')
{
    include 'Helper/LogReport.php';
    $GetSQL = "Select Value from PostKept where UserName = '" .$_COOKIE['UserName']. "'";
    $KeepResult = $conn->query($GetSQL);
    $KeepResults = $KeepResult->fetchALL(PDO::FETCH_ASSOC);

    $request = unserialize($KeepResults[0]['Value']);

    $DataReturn = json_encode(FilterSort::complex($request,$sqlConnect,$table,$primaryKey,$ColumnHeader,1));
    require './ExportAllToExcel.php';
Run Code Online (Sandbox Code Playgroud)

我还更改了保留查询的方式,现在还保留表名用户名,如下所示:

include 'DBConn.php';
$KeepPost = $_POST;                                     //POST holds all the data for the search
$KeepPost['length'] = -1;                               //-1 means pulling the whole table
$PostKept = serialize($KeepPost);                       //This takes the array of data and turns it into a string for storage in SQL
$SQLCheck = "select distinct UserName from PostKept";   //Gets all the distinct Usernames of users that have used the Report Dashboard.
$sth = $conn->query($SQLCheck);
$CheckedUser = $sth->fetchALL(PDO::FETCH_ASSOC);
foreach($CheckedUser as $User)
{
    foreach($User as $Index => $Who)
    {
        $FoundUsers[] = $Who;                           //Taking all the found users and placing them into a simpler array for searching later

    }
}

if(isset($_COOKIE['UserName']) && in_array($_COOKIE['UserName'],$FoundUsers))   //If the user already has an entry update it with new information
{
    $TSQL = "UPDATE PostKept set Value = '" .$PostKept. "', TableName = '" .$TableName. "' where UserName = '" .$_COOKIE['UserName']. "'";
}
else
{
    if(isset($_COOKIE['UserName']))     //If this is a new user
    {
        $TSQL = "INSERT into PostKept(Value, TableName, UserName) select '" .$PostKept. "','" .$TableName. "','" .$_COOKIE['UserName']. "'";
    }
    else        //If this is on the Prod site and the User info is not yet kept
    {
        $TSQL = "INSERT into PostKept(Value, TableName) select '" .$PostKept. "','" .$TableName. "'";
    }
}

$sth = $conn->prepare($TSQL);
$sth->execute();
Run Code Online (Sandbox Code Playgroud)

现在,这就是将数据发送到我拥有的ExportAllToExcel.php文件的全部组合,然后它依次创建该文件。