支持IE,FireFox,Chrome三大主流瀏覽器,通過js+Flash方式將table導出Excel文件


今天在做項目的時候,遇到了前端下載Excel的功能,結果原先的代碼,如下:

function generate_excel(tableid) {
        var table = document.getElementById(tableid);
        var html = table.outerHTML;
        window.open('data:application/vnd.ms-excel;base64,' + base64_encode(html));
}

此種寫法,只能支持FF,chrome,在IE下無法支持。在網上搜索了一下,也無法找到比較好的jquery插件,能夠同時跨三種平台,通過jquery方式將html的table導出Excel。

后來機緣巧合之下,發現一個Flash,能夠同時支持各種瀏覽器。對於並不排斥使用的flash的網站來說,也許是一個解決方案。

不過,目前使用下來,該方法有兩個缺點

1.firefox中需要允許該flash運行

2.IE中導出,excel行高稍許有些問題

下面是使用方法

flash的下載地址:https://github.com/dcneiner/Downloadify

示例代碼:

html中

<p id="downloadify">

<object id="downloadify_obj" width="100" height="30" type="application/x-shockwave-flash" name="downloadify_obj" data="../../Scripts/TableExport/downloadify.swf">
      <param name="allowScriptAccess" value="always">
      <param name="wmode" value="transparent">
      <param name="flashvars" value="queue_name=downloadify&width=100&height=30&downloadImage=images/download.png">
      </object>
</p>

其中,data="../../Scripts/TableExport/downloadify.swf",downloadImage=images/download.png"   需要改成自己的相應路徑

js中

<script type="text/javascript">// <![CDATA[
     Downloadify.create('downloadify', {
          filename: function () {
               return "Data.xls";
          },
          data: function () {
               var table = document.getElementById('Table');
               var html = table.outerHTML;
               return html;
          },
          onComplete: function () {
               alert('Your File Has Been Saved!');
          },
          onCancel: function () {
               alert('You have cancelled the saving of this file.');
          },
          onError: function () {
               alert('You must put something in the File Contents or there will be nothing to save!');
          },
          transparent: false,
          swf: '../../Scripts/TableExport/downloadify.swf',
          downloadImage: '../../Scripts/TableExport/download.png',
          width: 100,
          height: 30,
          transparent: true,
          append: false
});
// ]]></script>

其中,

filename的名字自己修改,

data中,寫自己table的名稱

swf: '../../Scripts/TableExport/downloadify.swf',
downloadImage: '../../Scripts/TableExport/download.png',

寫自己對應的路徑。其他的可以自己網上查詢api

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM