Search code examples
javascripthtmlexport-to-excel

Excel export not working on Firefox but working fine in google crome


The below given event is called to export the data in the table into an EXCEL , The code works like a charm in Chrome . In IE and Firefox i am not getting anything(File, error etc). Kindly assist me to go forward and export the file in all the browsers

$("[id$=myButtonControlID]").click(function(e) { 
    var result = 'data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=printHead]').html());
    var link = document.createElement("a");
    link.download = "Reports";
    link.href = result;
    link.click();
});

Solution

  • With Firefox you have to explicitly add the link element to the DOM before you can execute .click():

    $("[id$=myButtonControlID]").click(function(e) { 
        var result = 'data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=printHead]').html());
        var link = document.createElement("a");
        document.body.appendChild(link);  // You need to add this line
        link.download = "Reports";
        link.href = result;
        link.click();
    });
    

    The data: URI is supported from IE8. But it "cannot be used for navigation [...]" so I assume it will not work in an <a href="...">. See this link.