How to add row/column with value to datatables csv export - javascript

I am using jquery datatable to display data. I am also exporting a CSV file using the datatable. I need to be able to add a field and value to a specific location on the csv file that is exported. The field and value do not exist on the datatable so currently when I export it, it is only copying what is on the datatable. How do I add a field and value "Totals" to the csv when exported to row 7 column H?
$('#ar-table').dataTable({
'paginate': false,
'bDestroy': true,
'dom': 'Bfrtip',
'buttons': [
'print', 'csv', {
extend: 'excel', filename: '*', extension: '.xlsx',
}, {
extend: 'pdfHtml5',
orientation: 'landscape',
text: 'PDF',
title: 'Open A/R - ' + $('#customer-name').val() + ' - ' + today,
}, {
extend: 'pdfHtml5',
orientation: 'landscape',
text: 'PDF-L',
title: 'Open A/R - ' + $('#customer-name').val() + ' - ' + today,
},
],
'aLengthMenu': [[25, 50, 100, 200, -1], [25, 50, 100, 200, 'All']],
'iDisplayLength': -1,
});
DATATABLE VIEW
CSV EXPORT
[

I was able to solve this by using the customize key for datatables. Here is a what my code looks now. This is not using a dynamic variable yet. Hardcoded currently but this solves my initial problem.

Related

Datatables Bootstrap4 - Uncaught (in promise) Cannot extend unknown button type: create

I have a requirement to display a table, with all CRUD operations.
I am using DataTables for the first time. I have gone through so many post but people have used PHP, and I have no idea about PHP. I am just simply using Datatables with JS.
Please tell me If I am going in any wrong direction.
Anyway, here is the error I am getting.
My code is working fine, I am able to fetch Data. But I want to use inbuilt edit delete feature of Data tables.
Here is my Data table:
$('#table').DataTable(
{
data: userArray,
"lengthMenu": [[5, 10, 15, 20, -1], [5, 10, 15, 20, "All"]],
"pageLength": 10,
select:true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
],
columns: [
{ title: ' User ID' },
{ title: "firstName" },
{ title: 'Last Name' },
{ title: "Email" },
],
});
This is the error:
Uncaught (in promise) Cannot extend unknown button type: create
script-

Datatable does not works with Firebase

I am trying to display data in data in Datatable and allow the user to download in desired format. But it does not seem to work my data neither gets displayed nor gets downloaded. This is the code am using at the moment.
document.addEventListener("DOMContentLoaded", function(event) {
var dTable=$('#ex-table').DataTable({
"bDestroy": true,
dom: 'lfrtipB',
buttons: [
{
extend: 'copyHtml5',
title: 'Records'
},
{
extend: 'csvHtml5',
title: 'Records'
},
{
extend: 'excelHtml5',
title: 'Records'
},
{
extend: 'pdfHtml5',
title: 'Records'
},
'print'
],
lengthMenu: [[5, 20, 50, -1], [5, 20, 50, "All"]]
});
});
var databaseRef = firebase.database().ref("users/");
var table = $('#ex-table').DataTable();
databaseRef.on("child_added", function(data) {
var storageObj = data.val();
var dataSet = [storageObj.Department, storageObj.EmpId, storageObj.Name, storageObj.Position];
table.rows.add([dataSet]).draw();
});
Here is the codepen https://codepen.io/jagrutitiwari/pen/WYBWVy for the code I am trying. Where am I going wrong?
Update:
Screenshot of my users node:
Update2
Security rules:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Update 3
If I add dataSrc to Datatable it works but I cannot see the exports buttons in Datatable now.
document.addEventListener("DOMContentLoaded", function(event) {
var dTable=$('#ex-table').DataTable({
"bDestroy": true,
dom: 'lfrtipB',
data: dataSrc,
buttons: [
{
extend: 'copyHtml5',
title: 'Records'
},
{
extend: 'csvHtml5',
title: 'Records'
},
{
extend: 'excelHtml5',
title: 'Records'
},
{
extend: 'pdfHtml5',
title: 'Records'
},
'print'
],
lengthMenu: [[5, 20, 50, -1], [5, 20, 50, "All"]]
});
});
With your security rules, your users need to be authenticated in order to read (and write to) the database.
With the code you show in your question (an excerpt of your entire HTML page, I guess), it seems that you don't ask the users to authenticate, therefore you don't get any record when you query the database.
You should either integrate an authentication mechanism, for example using FirebaseUI Auth (see https://github.com/firebase/firebaseui-web), or, if your database is in test, give a try with "public" rules, like:
{
"rules": {
".read": true,
".write": true
}
}

Data Attrbute - get and set in jquery

I have a number of tables on my page with the data attribute that I need to access in my document ready function, as follows, and also I show the HTML.
$('.accountsHoldingTable').DataTable({
dom: 'tB',
responsive: true,
"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
buttons: [
{
extend: 'excelHtml5',
filename: "Positions " + $(this).data("ttitle") + " " + today.toDateString()
}
],
});
<table id = "accountsHoldingTable"
data-ttitle = "my file name"
class = "headerSet table table-bordered display hover no-wrap dataTables accountsHoldingTable"
style = "width: 100%">
However, this gives me a result of
"Positions undefined Mon Dec 04 2017 (2).xlsx"
How do I do this properly so that undefined is replaced by the data-ttitle value?
I would guess that you are using this in the wrong context. See if this code accomplishes what you are are attempting to achieve:
$('.accountsHoldingTable').each(function(i, val) {
$(this).DataTable({
dom: 'tB',
responsive: true,
lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]],
buttons: [
{
extend: 'excelHtml5',
filename: "Positions " + $(this).data("ttitle") + " " + today.toDateString()
}
]
});
});

Datatables destroy function error

I'm using datatables.js for creating a report table. In my report page there are some filters. When apply any of filters my service returns data that has different column count. Because of this I'm destroying and recreating table. But an error occurs like Unable to get property 'style' of undefined or null reference.
var htmlTable = "<table class='display responsive no-wrap cell-border compact' style='margin: 0 !important' width='100%' id='policyTable'>" +
"<thead>" +
"<tr class='cell-border custom-header-footer tableHeaders' id='tableHeaders'>" +
"<th>Policy Details</th>" +
"</tr>" +
"</thead>" +
"</table>";
function InitAndLoadTableData(tableData, tableId, exportTitle) {
if ($.fn.DataTable.fnIsDataTable("#" + tableId)) {
var oldTable = $("#" + tableId).DataTable();
oldTable.destroy(true);
$("#divFor_" + tableId).append(htmlTable);
}
var table = $('#' + tableId)
.DataTable({
data: tableData,
dom: "<'row' <'col-md-12'B>><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
"searching": false,
"paging": false,
"info": false,
"ordering": false,
//destroy: true,
responsive: true,
processing: false,
columns: tableColumns,
buttons: [
{ extend: 'copy', className: 'btn red btn-outline', title: exportTitle },
{ extend: 'pdf', className: 'btn green btn-outline', title: exportTitle },
{ extend: 'excel', className: 'btn yellow btn-outline', title: exportTitle },
{ extend: 'csv', className: 'btn purple btn-outline', title: exportTitle }
]
});
table.buttons().container().appendTo($('.col-md-12:eq(0)', table.table().container()));
}
instead you please try this...
$('#example').DataTable( {
destroy: true,
// all the other stuff you want to perform
} );
I ran into the same issue - the intent was the same as the columns are dynamic.
I finally had to use the following code:
let table = $("#table-id").DataTable();
table.clear();
table.destroy();
// Once you know the columns, recreate by calling DataTable initializer
// Another important part - I do remove and recreate <th> based on received columns
// or we get a weird 'style' error because of mismatch between data and table columns.
The table.clear() call was the missing piece - without it, the existing HTML was not being removed. Passing destroy: true within DataTable constructor was useless and table.destroy did the trick.

Remove columns when exporting data when using datatable.net

I'm working on a project and i wanted to remove specific columns when exporting a table to pdf. So i used the code from datatables.net and here is my code for exporting
<script type="text/javascript">
$(document).ready(function() {
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var d = day + "-" + month + "-" + year;
$('#detailTable').DataTable( {
dom: 'Bfrtip',
buttons: [
{
extend: 'excelHtml5',
title: d+ ' Purchase Orders'
},
{
extend: 'csvHtml5',
title: d+ ' Purchase Orders'
},
{
extend: 'pdfHtml5',
title: d+ ' Purchase Orders',
orientation: 'landscape',
pageSize: 'LEGAL'
}
]
} );
});
I made it landscape since the table is kinda long and here is the output of the pdf i exported (I censored some values sorry for that)
Is there a way that i can remove that column where the values are 'edit'?
Thanks in advance
I prefer to utilize HTML to control the feel of my table which reduces the Javascript I need to write for common implementations of the Datatables so instead of utilizing specific column numbers (columns: [0, 1, 2]) I utilize a jQuery selector.
Specifically in my software I have columns for button actions, that generally look miserable in the
$.extend(true, $.fn.dataTable.defaults, {
dom: 'Bfrtlip',
lengthMenu: [[10, 25, 50, 250, -1], [10, 25, 50, 250, "All"]],
buttons: [
{
extend: 'copy',
exportOptions: {
columns: "thead th:not(.noExport)"
}
},
{
extend: 'excel',
exportOptions: {
columns: "thead th:not(.noExport)"
}
},
{
extend: 'csv',
exportOptions: {
columns: "thead th:not(.noExport)"
}
},
{
extend: 'print',
exportOptions: {
columns: "thead th:not(.noExport)"
}
}
//'copy', 'excel', 'csv', 'print' // , 'pdf' - Wait for next PDFMake release because of this bug https://github.com/bpampuch/pdfmake/pull/443
]
});
now my table:
<table>
<thead>
<tr>
<th>First Column</th>
<th>Second Column</th>
<th class="noExcel">Column to Hide</th>
<th>Fourth Column</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Column value</td>
<td>Second Column value</td>
<td>Column to Hide value</td>
<td>Fourth Column value</td>
</tr>
</tbody>
</table>
When the $("table").Datatables() is called it will have buttons for Copy > Excel > CSV > Print but each of them will ignore the 3rd column which has the class "noExport".
Yes you can set column index to hide column for exporting from datatable, You have to add column option in button attribute like following example :-
$('#datatable').dataTable({
"sScrollY": "350px",
"bPaginate": false,
"sDom": 'lfrtip<"clear spacer">T',
"oTableTools": {
"sSwfPath": "/flash/copy_cvs_xls_pdf.swf",
"aButtons": [
{
"sExtends": "copy",
"mColumns": [0, 1, 3, 4]
},
{
"sExtends": "csv",
"mColumns": [0, 1, 3, 4]
},
{
"sExtends": "pdf",
"mColumns": [0, 1, 3, 4]
},
{
"sExtends": "print",
"mColumns": [0, 1, 3, 4]
},
]
}
});
You can visit these url for more help
https://datatables.net/forums/discussion/3210/tabletools-how-to-hide-columns-when-exporting-copying
It may help you.

Categories