• 支持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',
               100,
              height: 30,
              transparent: true,
              append: false
    });
    // ]]></script>

    其中,

    filename的名字自己修改,

    data中,写自己table的名称

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

    写自己对应的路径。其他的可以自己网上查询api

  • 相关阅读:
    MAC OS系统替换homebrew使用阿里云的镜像源
    Javascript 交换两个变量的值
    Vue 中的 ref $refs
    Bluetooth M590 mouse problem Ubuntu
    Ubuntu 蓝牙鼠标的问题
    视频分享
    Vue项目中的文件/文件夹命名规范
    js打印div指定区域内容
    IntelliJ IDEA 配置
    idea安装
  • 原文地址:https://www.cnblogs.com/tfiremeteor/p/5650653.html
Copyright © 2020-2023  润新知