jquery - table2excel 插件和 IE 11

标签 jquery asp.net-mvc excel

在我的 MVC 4 应用程序中,我使用 jquery.table2excel.js 插件将表格内容下载到 Excel:

;(function ( $, window, document, undefined ) {
    var pluginName = "table2excel",

    defaults = {
        exclude: ".noExl",
                name: "Table2Excel"
    };

    // The actual plugin constructor
    function Plugin ( element, options ) {
            this.element = element;
            // jQuery has an extend method which merges the contents of two or
            // more objects, storing the result in the first object. The first object
            // is generally empty as we don't want to alter the default options for
            // future instances of the plugin
            //
            this.settings = $.extend( {}, defaults, options );
            this._defaults = defaults;
            this._name = pluginName;
            this.init();
    }

    Plugin.prototype = {
        init: function () {
            var e = this;

            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]--></head><body>",
                table: {
                    head: "<table>",
                    tail: "</table>"
                },
                foot: "</body></html>"
            };

            e.tableRows = [];

            // get contents of table except for exclude
            //$(e.element).each( function(i,o) {
            //    var tempRows = "";
            //    $(o).find("tr").not(e.settings.exclude).each(function (i,o) {
            //        tempRows += "<tr>" + $(o).html() + "</tr>";
            //    });
            //    e.tableRows.push(tempRows);
            //});
            $(e.element).each(function (i, o) {
                var tempRows = "";
                $(o).find("tr").not(e.settings.exclude).each(function (i, o) {
                    if (e.settings.columns.length == 0) {
                        tempRows += "<tr>" + $(o).html() + "</tr>";
                    } else {
                        var row = "";
                        e.settings.columns.forEach(function (colIndex) {
                            //is it a thead or tbody row?
                            if ($(o).find('th').length > 0) {
                                row += $(o).find('th:eq(' + colIndex + ')')[0].outerHTML;
                            } else {
                                row += $(o).find('td:eq(' + colIndex + ')')[0].outerHTML;
                            }
                        })
                        tempRows += '<tr>' + row + '</tr>';
                    }
                });
                e.tableRows.push(tempRows);
            });

            e.tableToExcel(e.tableRows, e.settings.name);
        },

        tableToExcel: function (table, name) {
            var e = this, fullTemplate="", i, link, a;

            e.uri = "data:application/vnd.ms-excel;base64,";
            //e.uri = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,";
            e.base64 = function (s) {
                return window.btoa(unescape(encodeURIComponent(s)));
            };
            e.format = function (s, c) {
                return s.replace(/{(\w+)}/g, function (m, p) {
                    return c[p];
                });
            };
            e.ctx = {
                worksheet: name || "Worksheet",
                table: table
            };

            fullTemplate= e.template.head;

            if ( $.isArray(table) ) {
                for (i in table) {
                    //fullTemplate += e.template.sheet.head + "{worksheet" + i + "}" + e.template.sheet.tail;
                    //fullTemplate += e.template.sheet.head + name + i + "" + e.template.sheet.tail;
                    fullTemplate += e.template.sheet.head + name + "" + e.template.sheet.tail;
                }
            }

            fullTemplate += e.template.mid;

            if ( $.isArray(table) ) {
                for (i in table) {
                    fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail;
                }
            }

            fullTemplate += e.template.foot;

            for (i in table) {
                e.ctx["table" + i] = table[i];
            }
            delete e.ctx.table;

            if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
            {
                if (typeof Blob !== "undefined") {
                    //use blobs if we can
                    fullTemplate = [fullTemplate];
                    //convert to array
                    var blob1 = new Blob(fullTemplate, { type: "text/html" });
                    window.navigator.msSaveBlob(blob1, getFileName(e.settings) );
                } else {
                    //otherwise use the iframe and save
                    //requires a blank iframe on page called txtArea1
                    txtArea1.document.open("text/html", "replace");
                    txtArea1.document.write(e.format(fullTemplate, e.ctx));
                    txtArea1.document.close();
                    txtArea1.focus();
                    sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings) );
                }

            } else {
                link = e.uri + e.base64(e.format(fullTemplate, e.ctx));
                a = document.createElement("a");
                a.download = getFileName(e.settings);
                a.href = link;

                document.body.appendChild(a);

                a.click();

                document.body.removeChild(a);
            }

            return true;
        }
    };

    function getFileName(settings) {
        return ( settings.filename ? settings.filename : "table2excel") + ".xls";
    }

    $.fn[ pluginName ] = function ( options ) {
        var e = this;
            e.each(function() {
                if ( !$.data( e, "plugin_" + pluginName ) ) {
                    $.data( e, "plugin_" + pluginName, new Plugin( this, options ) );
                }
            });

        // chain jQuery functions
        return e;
    };

})( jQuery, window, document );

我的 View 脚本:

<script type="text/javascript">
    $(function () {
        $('#btnExportToExcel').click(function () {
            $("#divTableHolder").table2excel({
                exclude: ".noExl",
                name: "Application Versions",
                filename: "Application Versions",
                columns: [0, 1, 2, 3]
            });
        })
    })
</script>

该函数在 Chrome 和 Firefox 中运行良好,但当我尝试在 Internet Explorer 11 中运行它时,我在文件中看到的唯一结果是 {table0}。 工作表名称和文件名设置正确。所以看来表格的内容没有正确加载到文件中。

另一件事是,当我打开文件时,会出现警告:

"The file you are trying to open is in a different format than specified by the extension..."

我仍然可以通过单击"is"来打开该文件。我将脚本或文件名的扩展名更改为 xlsx,但在这种情况下,我什至无法打开该文件。 此警告出现在 Chrome、Firefox 和 IE 中,但我可以接受。对我来说最重要的是在 IE 11 中生成报告。

最佳答案

我也遇到了同样的问题。通过在 table2excel.js 中添加以下代码来解决此问题

fullTemplate = e.format(fullTemplate, e.ctx);

        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
        {
            if (typeof Blob !== "undefined") {
                //use blobs if we can
                fullTemplate = [fullTemplate];
                //convert to array
                var blob1 = new Blob(fullTemplate, { type: 'text/html' });
                window.navigator.msSaveBlob(blob1, 'Download.xls');
                return (true);
            } else {
                //otherwise use the iframe and save
                //requires a blank iframe on page called txtArea1
                txtArea1.document.open("text/html", "replace");
                txtArea1.document.write(fullTemplate);
                txtArea1.document.close();
                txtArea1.focus();
                sa = txtArea1.document.execCommand("SaveAs", true, "Download.xls");
            }

        } else {
            //sa = e.uri + e.base64(fullTemplate);//window.open(e.uri + e.base64(fullTemplate));
            link = e.uri + e.base64(e.format(fullTemplate, e.ctx));
                a = document.createElement("a");
                a.download = getFileName(e.settings);
                a.href = link;

                document.body.appendChild(a);

                a.click();

                document.body.removeChild(a);
        }

        return (sa);

关于jquery - table2excel 插件和 IE 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34272110/

相关文章:

vba - Excel - 复制条件格式、删除规则、保留格式

excel - Excel VBA中引用相邻单元格的最有效方法是什么?

JQuery 语言下拉选择器

php - Laravel:通过 AJAX 无表单发送数据到 Controller

javascript - MVC ASP.Net Javascript - 如果 Url 没有 id,如何使用 javascript 函数隐藏按钮

c# - ASP.NET MVC 将 ID 传递给 ActionLink

javascript - KendoUI-Editor 显示标记而不是格式化的 html

javascript - 如何仅触发一次引导模式并使用浏览器本地存储来检测模式是否已被触发

asp.net-mvc - 如何使用 ASP.NET MVC 在客户端生成 url?

sql-server - 如何使用SSIS读取Excel电子表格中的变量值