使用 Javascript 将 table 导出到 MS Excel,在 MS Edge 上无法正常工作

Export table to MS Excel with Javascript, on MS Edge not working

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

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

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

谢谢。

您目前无法在 Internet Explorer 或 Microsoft Edge 中导航到 security purposes. However, blobs can be downloaded or saved using msSaveBlob or msSaveOrOpenBlob 的数据 url。

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

(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 是否可用。如果是,就使用它们,如果不是,你可以走另一条路。

希望对您有所帮助。