2015-12-14 4 views
2

В моем приложении MVC 4 Я jquery.table2excel.js используя плагин для загрузки содержимого таблицы в Excel:table2excel плагин и IE 11

;(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); 

Мой скрипт вида:

<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}. Имя листа и имя файла установлены правильно. Поэтому кажется, что содержимое таблицы неправильно загружено в файл.

Другое дело, что когда я открываю предупреждение файл, он появляется:

«Файл, который вы пытаетесь открыть в другом формате, чем указанным расширением ...»

Я могу открыть файл в любом случае, нажав «Да». Я изменил расширение либо в скрипте, либо для имени файла в xlsx, но в этом случае я даже не могу открыть файл. Это предупреждение появляется в Chrome, Firefox и IE, но я могу жить с этим. Самое главное для меня, чтобы создать отчет в IE 11.

+0

вы можете пойти на IFRAME http://stackoverflow.com/a/25280337/2037335 – Jude

ответ

1

Я сталкиваюсь с той же проблемой. Она решается путем добавления сильфона кода в 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); 
+0

работал как шарм. Замените всю функцию из строки 101 этим. – jmcg

0

Добавить это в строке 101 в table2excel.js

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