Surendra Surendra - 1 month ago 5
Javascript Question

Is there any way to export html table into Excel working in all browsers?

I used below code for that but its works only in Firefox.
It also not allow customize exported file name. It takes a random file name.

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" ><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, filename) {
var OriginalHTML = $('#' + table + '').html();
if (!table.nodeType) {

table = document.getElementById(table);
$(table).find(".EditColumns").remove();
}
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
$(table).html(OriginalHTML);

//window.location.href = uri + base64(format(template, ctx))
document.getElementById("aExportTable").href = uri + base64(format(template, ctx));
document.getElementById("aExportTable").download = filename;
document.getElementById("aExportTable").click();
HighlightSelectedRow();
}
})();

Answer

Try a blob. Should work in IE10+, Chrome/Safari and Fx

  window.URL = window.URL || window.webkitURL;
  var blob = new Blob([format(template, ctx)]); // format is part of OP's code
  var blobURL = window.URL.createObjectURL(blob);
  if (blobURL) {
    $("<a/>")
      .attr("href", blobURL)
      .attr("download", fileName)
      .text("Download "+fileName+" for import")
      .appendTo('#downloadLink');
  }
  else {
    $("#downloadLink").html("Please cut and paste from the table below");
  }  
Comments