I need to add a button to download the datatable content as a text file. I have only one column in the datatable. My code is given below. Copy, excel, csv, pdf and print are working properly with below code.
$(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
}
],
});
});
The built-in DataTables buttons don't support exporting a single column as a plain text file. You can however achieve this by defining your own button with a custom action.
The snippet below should achieve what you are looking for, it can be added to the buttons array passed to DataTable on setup. This adds a button named 'TXT' which takes the filtered values from the first column in the table, joins then with CR+LF, and then triggers a download of the result as a .txt file.
{
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);
}
}
A working example can be seen at https://jsfiddle.net/a3eucptL/.