【问题标题】:Export table to MS Excel with Javascript, on MS Edge not working使用 Javascript 将表格导出到 MS Excel,在 MS Edge 上不起作用
【发布时间】:2015-12-01 20:16:11
【问题描述】:

我一直在使用link 中显示的相同代码将表格从 HTML 导出到 Excel,它在许多浏览器中运行良好。

当我在全新的 MS Edge 网络浏览器上测试它时,问题就来了,它打开了一个新的 空白 标签,就是这样。没有控制台错误,没有弹出警告,什么都没有。正如我所说,link 有一种方法可以在 IE 中处理导出到 Excel。

所以我想知道你们中是否有人知道支持新 Microsoft Edge 浏览器的类似技巧。

谢谢。

【问题讨论】:

    标签: javascript html excel microsoft-edge


    【解决方案1】:

    您目前无法在 Internet Explorer 或 Microsoft Edge 中导航到 security purposes 的数据 URL。但是,可以使用 msSaveBlob or msSaveOrOpenBlob 下载或保存 blob。

    我在下面为您准备了一个基本示例:

    (function () {
    
      // Generate our CSV string from out HTML Table
      var csv = tableToCSV( document.querySelector( "#sites" ) );
      // Create a CSV Blob
      var blob = new Blob( [ csv ], { type: "text/csv"} );
    
      // Determine which approach to take for the download
      if ( navigator.msSaveOrOpenBlob ) {
        // Works for Internet Explorer and Microsoft Edge
        navigator.msSaveOrOpenBlob( blob, "output.csv" );
    
      } else {
    
        // Attempt to use an alternative method
        var anchor = document.body.appendChild(
          document.createElement( "a" )
        );
        // If the [download] attribute is supported, try to use it
        if ( "download" in anchor ) {
          anchor.download = "output.csv";
          anchor.href = URL.createObjectURL( blob );
          anchor.click();
        }
    
      }
    
      function tableToCSV( table ) {
        // We'll be co-opting `slice` to create arrays
        var slice = Array.prototype.slice;
    
        return slice.call( table.rows ).map(function ( row ) {
          return slice.call( row.cells ).map(function ( cell ) {
            return '"t"'.replace( "t", cell.textContent );
          }).join( "," );
        }).join( "\r\n" );
    
      }
    
    }());
    

    在线测试:http://jsfiddle.net/jonathansampson/nc4k4hz8/

    您需要执行一些功能检测以查看msSaveBlobmsSaveOrOpenBlob 是否可用。如果是,请使用它们,如果不是,您可以沿着另一条路线继续。

    我希望这会有所帮助。

    【讨论】:

    • 是否可以使用 excel 扩展名(xls、xlsx)保存文件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多