4

I'm Using This Function while download i need to give default name current date but it's giving default name as download i need to change the name how i can change?

var tableToExcel = (function() {
    var uri = 'data:application/vnd.ms-excel;
    base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c)
    { 
      return s.replace(/{(\w+)}/g, function(m, p) { return c[p];  
    }) 
  }

  return function(table, name) {

     if (!table.nodeType) table = document.getElementById(table)

     var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}

    window.location.href = uri + base64(format(template, ctx))
 }

})()
Jatin
  • 3,065
  • 6
  • 28
  • 42
Raj
  • 55
  • 2
  • 5

1 Answers1

4

Working Demo

Based on this answer you have to do the following:

*-Add a hidden link to your html in order to use the download attribute supported by modern browsers:

<a id="dlink"  style="display:none;"></a> 

*-Add a third parameter specifying the file name for the function caller, here we will call the file 'myfile.xls':

<input type="button" onclick="tableToExcel('tablename', 'name', 'myfile.xls')" value="Export to Excel">

*-Add the third parameter to the function deceleration:

 return function (table, name, filename)

*-Remove the following line, we are no longer biding the download to window location href directly.

 window.location.href = uri + base64(format(template, ctx))

*-Add the following 3 lines to replace the removed line, we will assign the download to the hidden link we added to the html, then we will bid that link to the browser default download function which allows filename attribute:

            document.getElementById("dlink").href = uri + base64(format(template, ctx));
            document.getElementById("dlink").download = filename;
            document.getElementById("dlink").click();
Community
  • 1
  • 1
Mohammed Joraid
  • 6,202
  • 2
  • 27
  • 38
  • @AakashGoplani Well, I wrote that answer in 2014 so I'm not sure what has changed in browsers technology since that time. I just tested the fiddle on Mozilla Firefox, Microsoft Edge, and Google Chrome. Chrome and Firefox were successful, Edge failed to even prompt to download, the cursor kept circling indicating loading but no action happened. – Mohammed Joraid Nov 09 '17 at 06:33