Export HTML table to Excel keeping styles

Asked

Viewed 947 times

3

I would like to know how to export a table of my html code to excel keeping the formatting (colors, borders, etc). I am 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 table data and creates the spreadsheet, but without any formatting (for example this one below). How to apply CSS in Excel too? Thank you!

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;

}

1 answer

1

I got a lot of that a few years ago, the only solution was to declare inline styles.

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

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

Ps.: I will search the sources where I had searched and include in the answer.

  • Well, that’s too bad, but thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.