Export Html Table to excel and keep css styles

后端 未结 3 1127
误落风尘
误落风尘 2021-01-04 18:31

I\'m using excel web queries to export an html table (mvc view) to excel. How do I get it to carry across the css styles? If I set class=\"redLabel\" it doesn\'

3条回答
  •  盖世英雄少女心
    2021-01-04 18:45

    Excel does support using css styling, but only if there is one class on the element. If there are multiple classes then it will not do any style on the element, see CSS style class not combining in Excel

    Having said that, this is the code I put together to grab all the styles on a page and export an HTML table. It's a brute force, grab everything approach, but you could probably pair it down if you know the specifics. The function returns a jQuery Promise. From that you can do whatever with the result.

    function excelExportHtml(table, includeCss) {
    
        if (includeCss) {
            var styles = [];
    
            //grab all styles defined on the page
            $("style").each(function (index, domEle) {
                styles.push($(domEle).html());
            });
    
            //grab all styles referenced by stylesheet links on the page
            var ajaxCalls = [];
            $("[rel=stylesheet]").each(function () {
                ajaxCalls.push($.get(this.href, '', function (data) {
                    styles.push(data);
                }));
            });
    
            return $.when.apply(null, ajaxCalls)
                    .then(function () {
                        return "\n" + table.outerHTML + "";
                    });
        }
        else {
            return $.when({ owcHtml: table.outerHTML })
                    .then(function (result) {
                        return "" + result.owcHtml + "";
                    });
        }
    }
    

提交回复
热议问题