SPFx - Display export buttons for Excel, CSV, PDF, Copy, Print, Column visibility in Datatable.net using Typescript
This is an example to display export buttons in datatables.net using typescript in SPFx.
Install following references using 'npm'.
npm install jquery
npm install jquery-ui
npm install datatables.net
npm install datatables.net-buttons
npm install datatables.net-buttons-dt
npm install jszip
npm install pdfmake
Import references in webpart file .
import * as $ from 'jquery';
import 'jquery-ui';
import 'DataTables.net';
import 'datatables.net-buttons';
import 'datatables.net-buttons-dt';
import 'pdfmake/build/pdfmake';
import * as JSZip from 'jszip'; //most important for excel button
//Export to PDF
import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";
pdfMake.vfs = pdfFonts.pdfMake.vfs; // most important for PDF
require('../../../node_modules/datatables.net-dt/css/jquery.dataTables.min.css');
require('../../../node_modules/datatables.net-dt/js/dataTables.dataTables.min.js');
require('../../../node_modules/datatables.net-buttons-dt/css/buttons.dataTables.min.css');
require('../../../node_modules/datatables.net-buttons-dt/js/buttons.dataTables.min.js');
require('../../../node_modules/jszip/dist/jszip.min.js');
require('../../../node_modules/pdfmake/build/pdfmake.min.js');
require('../../../node_modules/pdfmake/build/vfs_fonts.js');
require('../../../node_modules/datatables.net-buttons/js/dataTables.buttons.min.js'); /
require('../../../node_modules/datatables.net-buttons/js/buttons.colVis.min.js'); //Column visibility
require('../../../node_modules/datatables.net-buttons/js/buttons.html5.min.js'); //# HTML 5 file export
require('../../../node_modules/datatables.net-buttons/js/buttons.flash.min.js'); // # Flash file export
require('../../../node_modules/datatables.net-buttons/js/buttons.print.min.js'); // # Print view button
Here is the function I have created which you can call when you want to initialize datatable
private bindDatatable() {
window["JSZip"] = JSZip; // most most important step to see excel button
$('#tableId').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'copy',
text: "Copy",
filename: "Test", //You can write function and call it here for dynamic logic of file name
},
{
extend: 'csv',
text: "CSV",
filename: "Test",
extension: '.csv',
},
{
extend: 'excel',
text: "Excel",
filename: "Test",
extension: '.xlsx',
},
{
extend: 'print',
text: "Print",
filename: "Test",
},
{
extend: 'pdf',
text: "PDF",
filename: "Test",
},
{
extend: 'colvis',
text: "Show/hide columns",
},
],
});
};
}
Or if you don't want to modify anything in extended button, you can simply write as per Datatable.net
$(
'#example'
).DataTable( {
dom:
'Bfrtip'
,
buttons: [
'copy'
,
'csv'
,
'excel'
,
'pdf'
,
'print'
]
} );
Thank you for reading..!! :)
This is exact what I am looking for. Thank you for posting this
ReplyDelete