How to trigger excel export from an external button?
How to trigger excel export from an external button?
frankyy
Posts: 8Questions: 4Answers: 0
Description of problem:
Hello, I'm trying to trigger the excelHtml5 functionality from an external button. I've achieved that but I for example I couldn't customize the filename, it downloads the file with a name of "xlsx.xlsx".
This is my table definition:
const exportFileName = "test_filename";
const table = $table.DataTable({
data: tableData,
columnDefs: columnDefs,
dom: 'Bfrtip',
scrollX: true,
scrollCollapse: false,
paging: false,
info: false,
colReorder: true,
layout: {
topStart: {
buttons: [{
extend: 'excelHtml5',
title: null,
filename: function () {
return exportFileName;
}
}]
}
},
searching: false,
columnControl: [['myButton', 'orderAsc', 'orderDesc', 'order']],
});
I hid the excelHtml5 button using css and tried to trigger it via an external button like that:
const triggerExcelExport = (tableInstance) => {
if (!tableInstance) {
return false;
}
const tryTrigger = (selector) => {
if (!tableInstance.button || typeof tableInstance.button !== 'function') {
return false;
}
const api = tableInstance.button(selector);
if (api && api.length && typeof api.trigger === 'function') {
api.trigger();
return true;
}
return false;
};
if (tryTrigger('.buttons-excel')) {
return true;
}
const tableContainer = (tableInstance.table && typeof tableInstance.table === 'function')
? $(tableInstance.table().container())
: $();
const fallbackButton = tableContainer.find('.dt-button.buttons-excel');
if (fallbackButton.length) {
fallbackButton.eq(0).trigger('click');
return true;
}
return false;
};
$(document).on('click', '[id^="excelExport_"]', function(e) {
e.preventDefault();
const table_id = $(this).attr('table-id');
const table = allTables[table_id];
if (!table) {
console.error('DataTable instance not found for ID:', table_id);
return;
}
if (!triggerExcelExport(table)) {
console.error('Excel button not found! Make sure JSZip is loaded.');
alert('Excel export not available. Please contact support (Missing JSZip).');
}
});
Package versions:
* Included libraries:
* jQuery 3.7.0, JSZip 3.10.1, pdfmake 0.2.7, DataTables 2.3.5, Buttons 3.2.5, HTML5 export 3.2.5, ColReorder 2.1.2, ColumnControl 1.1.1, FixedColumns 5.0.5, FixedHeader 4.0.5, RowGroup 1.6.0, Select 3.1.3
*/
Answers
I solved the problem by removing the
dom: 'Bfrtip',option from the datatable initialization. Problem solved now thx.Yeah,
.
layoutanddomshouldn't be used together - they more or less do the same thing in different ways. That said, I'm surprised thatdomcaused this issue, but equally, if you've got it working now, that's all that mattersAllan