0

Is there a function out there that has the ability to download a HTML table in an Excel spreadsheet format, that's A. Written in native Javascript and B. Cross browser compliant back to IE8?

I have spend 2 days time searching for a solution, but to no avail.

Mike Resoli
  • 1,005
  • 3
  • 14
  • 37
  • 1
    I found this http://jsfiddle.net/terryyounghk/kpegu/ which uses jquery to export to csv (which in turn can be opened by excel and saved) – Andrew Bone Dec 17 '15 at 15:36
  • @AndrewBone thanks for that, but this doesn't include the table headers in the export.csv file. – Mike Resoli Dec 17 '15 at 15:39
  • 1
    The script was telling it not to include it, http://jsfiddle.net/link2twenty/KPEGU/4253/ I've added th to it now. – Andrew Bone Dec 17 '15 at 15:56

2 Answers2

1

I'm very skeptical that you're going to find an answer to this, but as a practical solution to the conversion problem, have you considered outputting HTML and converting within Excel?

Taken from this answer: https://stackoverflow.com/a/9575683/199700

Excel can change the format of the HTML file: To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub
Community
  • 1
  • 1
Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
0

@SamPopes answer from this thread is compatible with IE7+, Firefox and Chrome. I have edited his code so that you can pass your table as a function parameter, as I dynamically create my table via. document.createElemet('table').

function export(obj) {
  var tab_text="<table border='2px'><tr>";
  var textRange; var j=0;
  tab = obj; //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>";
  tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if you want links in your table
  tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if you want images in your table
  tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // removes input params

  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,"export.xls");
  } else { //other browser not tested on IE 11
      sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));            
      return (sa);
  }
}
Community
  • 1
  • 1
Mike Resoli
  • 1,005
  • 3
  • 14
  • 37