Export HTML table to Excel keeping styles

Question:

I would like to know how I can export a table from my html code to excel keeping the formatting (colors, borders, etc). I'm using the following function:

<script type="text/javascript">

function fnExcelReport() {
    var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
    tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';

    tab_text = tab_text + '<x:Name>Results</x:Name>';

    tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
    tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';

    tab_text = tab_text + "<table border='2px'; >";
    tab_text = tab_text + $('.biocompar').html() + $("#janelares1a").html()+ $("#janelares5a").html();
    tab_text = tab_text + '</table></body></html>';

    var data_type = 'data:application/vnd.ms-excel';

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        if (window.navigator.msSaveBlob) {
            var blob = new Blob([tab_text], {
                type: "application/csv;charset=utf-8;"
            });
            navigator.msSaveBlob(blob, 'Biorefinery WebTool Results.xls');
        }
    } else {
        $('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
        $('#test').attr('download', 'Biorefinery WebTool Results.xls');
    }

}
</script>

But when I activate the function it just sends the data from the table and creates the spreadsheet, but without any formatting (for example this one below). How to apply CSS in Excel too? Thanks!

td{
    width:30ch;
    height:3ch;
    background-color:#f0f8ff;
    border: 2px solid #151c14;
    font-family: "Muli";
    line-height: 5ch;
    color:#000;
    text-indent: 0.5em;
    transition: all 0.2s ease-in-out;

}

Answer:

I got hit a lot with this a few years ago, the only solution was to declare the styles inline anyway.

I remember that I had found a restriction where Excel only recognizes one class per element and in this case it would not do you to create a td{} , it would have to be like .nome{} and be declared as the only class of the element <td class="nome"> . If there is more than one he disregards them all.

And even so, don't expect a great visual enrichment, after all Excel is not an html browser, try to limit yourself to the basics… As if you were creating the style for an E-mail or Word.

Ps.: I will look for the sources where I had researched and include in the answer.

Scroll to Top