Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've been exporting a table from HTML to Excel using the very same code shown in this link and it worked pretty good in many browsers.

The problem comes when I test it on the brand new MS Edge web browser, it opens up a new blank tab, just that. No console error, no warning pop-up, nothing. As I said, in that link there's a way to handle exportation to Excel in IE.

So I wonder if anyone of you knows a similar trick to support the new Microsoft Edge browser.

Thanks.

like image 780
gingerEd Avatar asked Dec 01 '15 20:12

gingerEd


1 Answers

You cannot presently navigate to data-urls in Internet Explorer, or Microsoft Edge, for security purposes. However, blobs can be downloaded or saved using msSaveBlob or msSaveOrOpenBlob.

I've prepared a basic example for you below:

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

  }

}());

Test Online: http://jsfiddle.net/jonathansampson/nc4k4hz8/

You'll want to perform a bit of feature detection to see if msSaveBlob or msSaveOrOpenBlob are available. If they are, use them, and if they're not you can proceed along another route.

I hope this helps.

like image 65
Sampson Avatar answered Oct 07 '22 00:10

Sampson