2011-08-02 78 views
10

我正在使用Excel Web查詢將html表(mvc視圖)導出爲ex​​cel。我如何獲得它貫穿CSS樣式?如果我設置了class="redLabel",它不會解釋並將標籤設爲紅色。我必須在我的表中使用內聯樣式才能工作。有任何想法嗎?將Html表導出爲ex​​cel並保留css樣式

回答

6

據我所知,大多數Office程序不支持包含樣式,但只支持內聯樣式。

很可能您會被要求包含內聯樣式(導出很糟糕,幾乎像郵件樣式)。

2

Excel中不支持使用CSS樣式,但前提是元件上的一個類。如果有多個類,那麼它不會在元素上做任何樣式,請參閱CSS style class not combining in Excel

話雖如此,這是我放在一起的代碼,以獲取頁面上的所有樣式並導出HTML表格。這是一種蠻力,抓住一切的方法,但如果你知道具體細節,你可以將它配對。該函數返回一個jQuery Promise。從那你可以做任何結果。

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 "<html><style type='text/css'>" + styles.join("\n") + "</style>\n" + table.outerHTML + "</html>"; 
       }); 
    } 
    else { 
     return $.when({ owcHtml: table.outerHTML }) 
       .then(function (result) { 
        return "<html>" + result.owcHtml + "</html>"; 
       }); 
    } 
} 
1

您可以導出外部CSS樣式的表。這是我的解決方案申報文檔模板:

var e = this; 
var style = "<style></style"; //You can write css or get content of .css file 

e.template = { 
      head: "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>", 
      sheet: { 
       head: "<x:ExcelWorksheet><x:Name>", 
       tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>" 
      }, 
      mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->>"+style+"</head><body>", 
      table: { 
       head: "<table>", 
       tail: "</table>" 
      }, 
      foot: "</body></html>" 
     };