zoukankan      html  css  js  c++  java
  • js导出table(简单粗暴)

    html部分:

    <a href="javascript:;" type="button" id="export">导出</a>
        <table id="tableExcel">
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>IQ</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>阿杜</td>
                    <td>700</td>
                </tr>
            </tbody>
        </table>

    js部分:

    <script>
            $("#export").click(function () {
                tableToExcel("tableExcel", "export");
            })
    
            function tableToExcel(tableid,btnname) {
                var uri = 'data:application/vnd.ms-excel;base64,'
                    , template = '<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><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
                    , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
                    , format = function (s, c) { return s.replace(/{(w+)}/g, function (m, p) { return c[p]; }) }
                    //根据ID获取table表格HTML
                    var table = document.getElementById(tableid);
                    var ctx = { worksheet: 'Worksheet', table: table.innerHTML };
                    document.getElementById(btnname).href = uri + base64(format(template, ctx));
                    document.getElementById(btnname).download = '还阔以.xls';
            };
        </script>

    我把document.getElementById(btnname)换成window.location.href有问题,具体原因还在研究

    【改进版】

    我不想使用a标签,我想使用button,那么怎么使用href属性呢,

    实现代码如下,只需要修改两处:

    <button id="export">导出</button>   //改成按钮

    然后:

    var alink = document.createElement("a");
                alink.href = uri + base64(format(template, ctx));
                alink.download = '还阔以.xls';
                alink.click();

    这样的话,我直接新建一个element元素,然后将属性迁移到它上面

    记录编程的点滴,体会学习的乐趣
  • 相关阅读:
    《需求分析与系统设计》阅读笔记(四)
    《需求分析与系统设计》阅读笔记(三)
    每周总结(补)【2020/11/22】——自主学习MyBatis与Hive配置
    每周总结【2020/11/08】——————图表联动
    每周总结【2020/11/1】——动态生成树形组件,MapReduce,C++实现文法分析
    “公文流转系统 v1.0”
    统计文本文件(字母、单词、字符)
    动手动脑 第三周(一)
    动手动脑 第三周 (二)
    回文字符串判断
  • 原文地址:https://www.cnblogs.com/AduBlog/p/13841802.html
Copyright © 2011-2022 走看看