Home > Back-end >  DataTables Excel export with styles
DataTables Excel export with styles

Time:09-19

I am using DataTables compatible with Bootstrap. In a page I export table in Excel using “excelHtml5” and everything goes well.

In my case I want to set specific background colors on some cells, with “excelHtml5” there is a list of built in styles that we can use and I was able to apply them =>

$(document).ready(function() {
    $('#example').DataTable({
        dom: 'Bfrtip',
        buttons: [{
            extend: 'excelHtml5',
            customize: function(xlsx) {
                var sheet = xlsx.xl.worksheets['sheet1.xml'];
 
                $('row c', sheet).each( function () {
                    // Get the value
                    if ( $('is t', this).text() == 'New York' ) {
                        $(this).attr( 's', '20' );
                    }
                });
            }
        }]
    });
});

These built in styles are not enough for me, when I searched a lot I found responses that shows how to add new styles by modifying "xl/styles.xml" section in “buttons.html5.js” file, tried with many ways but no success I think there is some sort of internal cache or I am editing the wrong file.

So I found after another way by using this library enter image description here


The big downside with this approach is that you have manually edited the DataTables JavaScript - and those changes will be lost when you upgrade DataTables to a newer version. You will have to repeat the above edits.

You can avoid this by automating these edits in your DataTable's JavaScript code using customize: function( xlsx ).

That function gives you access to the Excel object (xlsx) inside which all the spreadsheet's data and styles are stored.

That is a larger, more complicated programming task.

But if you are interested, you can see an example showing a similar approach here: JQuery Datatable Excel export number format and also in various other questions on Stack Overflow.

  • Related