Export Handsontable to Excel (no csv)

Tags: #<Tag:0x00007f45281aefb8>

I made this code for export handsontable directly to Excel (not a CSV) .
You have just to call function fnExcelReport() on click.
The result is very simple but I think you are able to do better than me.
May be the handsontable team can do something for improve aspect of generated Excel.
Add comment to this thread for propose improvements.

<script>

    // This code export htCore class of Handsontable to Excel.
    // It works with Chrome, Firefox and Edge. Please don't ask about IE ;-P
    // Feel free to use this code and if you like it consider to offer me a coffe
    // Paypal : filippobesana(at)gmail.com


    function toDay() {
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth() + 1; //January is 0!

        var yyyy = today.getFullYear();
        if (dd < 10) {
            dd = '0' + dd;
        }
        if (mm < 10) {
            mm = '0' + mm;
        }
        return dd + '.' + mm + '.' + yyyy;
    }


    function fnExcelReport() {
        var tableClass = 'htCore';
        exportTableToExcel('' + tableClass + '');
    }


    function exportTableToExcel(tableClass) {
        var downloadLink;
        var dataType = 'application/vnd.ms-excel';
        //var tableSelect = document.getElementById(tableID);
        var tableSelect = document.getElementsByClassName(tableClass)[0];
        var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

        // Specify file name
        var filename = 'Export_' + toDay() +'.xls';

        // Create download link element
        downloadLink = document.createElement("a");

        document.body.appendChild(downloadLink);

        if (navigator.msSaveOrOpenBlob) {
            var blob = new Blob(['\ufeff', tableHTML], {
                type: dataType
            });
            navigator.msSaveOrOpenBlob(blob, filename);
        } else {
            // Create a link to the file
            downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
            // Setting the file name
            downloadLink.download = filename;
            //triggering the function
            downloadLink.click();
        }
    }
</script>

Hi @filippobesana

Thank you very much for the suggestion.