I want to export data in Excel using jQuery export button for datatables and here I have fixed grand total row at the bottom of table. The issue is: when I do sorting and then I export data into Excel, at that time the grand total also get sorted and it takes place somewhere at the middle of the data set - how can I fix that?
I want the grand total row as the last row always. I tried to remove the row and then appended at the last but it also didn't work here.
function loadDynamicTable(axis, value, data, vdata) {
$.ajax({
url: '@Url.Action("GetGridTableData", "Admin")',
data: { 'axis': axis, 'value': value, 'data': data },
type: 'POST',
"datatype": "json",
success: function (response) {
if (response.success) {
if ($.fn.DataTable.isDataTable('#dynamicTable')) {
dataTable.destroy();
}
$("#tableHeader").empty();
$("#tableBody").empty();
response.headers.forEach(function (header) {
$('#tableHeader').append('<th class="middle center white">' + header + '</th>');
});
let grandTotalRow = null;
let tableBodyHtml = "";
response.data.forEach(function (row) {
var rowHtml = '<tr>';
row.forEach(function (cell, index) {
if (index === 0) {
cell = cell === "Period Total" ? "Grand Total" : cell;
rowHtml += '<td>' + cell + '</td>';
} else {
//rowHtml += '<td class="text-right">' + Number(cell).toFixed(2) + '</td>';
let formattedValue = Number(cell).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
rowHtml += '<td class="text-right">' + formattedValue + '</td>';
}
});
rowHtml += '</tr>';
if (row[0] === "Grand Total") {
grandTotalRow = rowHtml;
} else {
tableBodyHtml += rowHtml;
}
});
$("#tableBody").html(tableBodyHtml);
if (grandTotalRow) {
$("#tableBody").append(grandTotalRow);
}
dataTable = $('#dynamicTable').DataTable({
destroy: true,
responsive: false,
//scrollX: true,
paging: false,
searching: false,
ordering: true,
autoWidth: false,
info: false,
order: [],
//dom: '<"top"lfB<"spacer">>rt<"bottom"ip><"clear">',
dom: 'Bfrtip',
buttons: [
{
extend: 'excel',
text: '<i class="fa fa-download" title="Export To Excel"></i>',
titleAttr: 'Export To Excel',
filename: function () {
return "Grid Report for " + data + "-" + vdata;
},
title: function () {
return "Grid Report for " + data + " - " + vdata;
},
}
],
initComplete: function (settings, json) {
$("#dynamicTable").wrap("<div style='overflow:auto; width:100%; position:relative;'></div>");
$(".dt-buttons").appendTo("#exportButtonContainer");
},
drawCallback: function () {
var api = this.api();
var rows = api.rows().nodes();
$(rows).each(function () {
if ($(this).find("td:first").text().trim() === "Grand Total") {
$(this).appendTo("#tableBody");
$(this).addClass("grand-total-row");
}
});
}
});
} else {
alert(response.message);
}
},
error: function () {
alert('Error fetching data.');
}
});
}