简体   繁体   中英

Export to Excel doesn't work in edge browser

This is the javascript function

function fnExcelReport()
    {
          var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
          var textRange; var j=0;
          tab = document.getElementById('tableID'); // id of table


          for(j = 0 ; j < tab.rows.length ; j++) 
          {     
                tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
                //tab_text=tab_text+"</tr>";
          }

          tab_text=tab_text+"</table>";

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

                 if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
                    {
                           txtArea1.document.open("txt/html","replace");
                           txtArea1.document.write(tab_text);
                           txtArea1.document.close();
                           txtArea1.focus(); 
                            sa=txtArea1.document.execCommand("SaveAs",true,"filename.xls");
                          }  
                  else                 //other browser not tested on IE 11
                      sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  


                      return (sa);
      }

and it will invoked on button click

<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>

This code works in Chrome, Firefox and IE. This is not working in Edge. Please help.

You are not catching Edge in your if

Edge will not have MSIE in the window.navigator.userAgent; it will have something like this

Mozilla/5.0 (Windows NT 10.0; <64-bit tags>) AppleWebKit/<WebKit Rev> (KHTML, like Gecko) Chrome/<Chrome Rev> Safari/<WebKit Rev> Edge/<EdgeHTML Rev>.<Windows Build>

So instead of checking for MSIE, you should be checking for Edge

Refer to this MS link User-agent string changes

Also take a look here

Refer to this fiddle https://jsfiddle.net/p8o42kdh/

Couple of points. 1) instead of indexOf I used match

ua.match(/Edge/)

2) To create file content I used blob

var blob = new Blob(["tab_text"], {type: 'data:application/vnd.ms-excel'});
window.navigator.msSaveBlob(blob, 'msSaveBlob_testFile.xls');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM