【问题标题】:How to export html body table to Excel?如何将html正文表导出到Excel?
【发布时间】:2016-11-05 23:07:22
【问题描述】:

我想导出除页脚之外的整个表格。反正还有不导出表的<tfoot>吗?

这是我的表格的骨架结构:

  <div id="table">
        <table data-filter="#filter" class="footable" style="background-color:white;">
            <thead>
                <tr>
                    <th>Employee ID</th>
                    <th>Branch Code</th>
                    <th>Client ID</th>
                    <th>Amount</th>
                    <th>Report Timestamp</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                if(count($result)==0)
                { echo "<tr><td colspan='5' style='text-align:center; font-weight:bold;'>No data available</td></tr>"; }
                else
                {
                for($i=0; $i<count($result); $i++){?>
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</td>
                    <td>5</td>
                </tr>

                <?php }
                }
                ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="8">
                        <div class="pagination pagination-centered"></div>
                    </td>
                </tr>
            </tfoot>
        </table>
        </div>

这是我在将表格导出到 excel 时使用的脚本:

<script>
(function () {
    var cache = {};

    this.tmpl = function tmpl(str, data) {
        // Figure out if we're getting a template, or if we need to
        // load the template - and be sure to cache the result.
        var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) :

        // Generate a reusable function that will serve as a template
        // generator (and which will be cached).
        new Function("obj",
            "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str.replace(/[\r\t\n]/g, " ")
            .split("{{").join("\t")
            .replace(/((^|}})[^\t]*)'/g, "$1\r")
            .replace(/\t=(.*?)}}/g, "',$1,'")
            .split("\t").join("');")
            .split("}}").join("p.push('")
            .split("\r").join("\\'") + "');}return p.join('');");

        // Provide some basic currying to the user
        return data ? fn(data) : fn;
    };
})();

var tableToExcel = (function () {
    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><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Sheet 1</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo/></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><body>{{for(var i=0; i<tables.length;i++){ }}<table>{{=tables[i]}}</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];
            })
        }
    return function (tableList, name) {
        if (!tableList.length > 0 && !tableList[0].nodeType) table = document.getElementById(table)
        var tables = [];
        for (var i = 0; i < tableList.length; i++) {
            tables.push(tableList[i].innerHTML);
        }
        var ctx = {
            worksheet: name || 'Worksheet',
            tables: tables
        };
        window.location.href = uri + base64(tmpl(template, ctx))
    }
})();
function download(){
    tableToExcel(document.getElementsByTagName("table"), "Sheet 1");
}
var btn = document.getElementById("btn");
btn.addEventListener("click",download);
</script>

编辑

好的,我已经尝试了上述脚本,结果如​​下: 知道为什么会这样吗?我需要网格线。我还需要删除页脚。我尝试了unix的第二个答案,但失败了。

这是代码:

    <script type="text/javascript">
        $(document).ready(function () {
            var something = '<table><tfoot></tfoot></table>'.replace(/<\/?tfoot>/g, '');
            $(something).appendTo('#table');
            $("#btn").click(function () {
                $("#table").btechco_excelexport({
                    containerid: "table"
                   , datatype: $datatype.Table
                });
            });
        });
    </script>

【问题讨论】:

    标签: javascript jquery html excel html-table


    【解决方案1】:

    你可能想尝试这样的事情

    var something = '<table><tfoot></tfoot></table>'.replace(/<\/?tfoot>/g, '');
    $(something).appendTo('something');
    

    并以某种方式将其合并到您的代码中。这将从您的 excel body html 内容中删除所有内容。

    【讨论】:

    • 对不起,我的意思是它会从你的 html 内容中删除 。
    • 如何将其合并到我的代码中?对不起,我不擅长 javascript。
    • 你可以试试这个。例如,如果您有此内容“
      更多嵌套标签
      ”;您可以将 div 之间的所有内容放入上述 var 中并运行 replace jquery 函数以摆脱您的 - 你需要以某种方式将此 html 字符串传递给你的 excel 生成器。
    • 呃,要我再写一个脚本吗?
    • 实际上我查看了@suchit 发布的内容,这似乎是一个更好的解决方案。部分原因是 lib 似乎是模块化的,编写良好且组织良好,并且有大量的实时示例。
    【解决方案2】:

    你可以在调用你的函数tableToExcel之前使用JQuerytable中删除tfoot元素

    $('table.footable').find('tfoot').remove().end();
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签