Exporting HTML table to Excel using Javascript

If CSV format is good for you, here is an example.

  • Ok...I just read a comment where you explicitly say it isn't good for you. My bad for not learning to read before coding.

As far I know, Excel can handle CSV.

function fnExcelReport() {
var i, j;
var csv = "";

var table = document.getElementById("table");

var table_headings = table.children[0].children[0].children;
var table_body_rows = table.children[1].children;

var heading;
var headingsArray = [];
for(i = 0; i < table_headings.length; i++) {
  heading = table_headings[i];
  headingsArray.push('"' + heading.innerHTML + '"');
}

csv += headingsArray.join(',') + ";\n";

var row;
var columns;
var column;
var columnsArray;
for(i = 0; i < table_body_rows.length; i++) {
  row = table_body_rows[i];
  columns = row.children;
  columnsArray = [];
  for(j = 0; j < columns.length; j++) {
      var column = columns[j];
      columnsArray.push('"' + column.innerHTML + '"');
  }
  csv += columnsArray.join(',') + ";\n";
}

  download("export.csv",csv);
}

//From: http://stackoverflow.com/a/18197511/2265487
function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}
<iframe id="txtArea1" style="display:none"></iframe>

Call this function on

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

<table id="table">
  <thead>
    <tr>
      <th>Head1</th>
      <th>Head2</th>
      <th>Head3</th>
      <th>Head4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>11</td>
      <td>12</td>
      <td>13</td>
      <td>14</td>
    </tr>
    <tr>
      <td>21</td>
      <td>22</td>
      <td>23</td>
      <td>24</td>
    </tr>
    <tr>
      <td>31</td>
      <td>32</td>
      <td>33</td>
      <td>34</td>
    </tr>
    <tr>
      <td>41</td>
      <td>42</td>
      <td>43</td>
      <td>44</td>
    </tr>
  </tbody>
</table>

On 2016-07-12, Microsoft pushed a security update for Microsoft Office. One of the effects of this update was to prevent HTML files from non-trusted domains from being opened by Excel, because they cannot be opened in Protected mode.

There is ALSO a registry setting that prevents Excel from opening files with the .XLS file extension whose contents do not match the official XLS file format, though it defaults to 'warn', not 'deny'.

Prior to this change, it was possible to save HTML data to a file with an XLS extension, and Excel would open it correctly - possibly giving a warning first that the file did not match the Excel format, depending on the user's value for the ExtensionHardening registry key (or related config values).

Microsoft has made a knowledge-base entry about the new behavior with some suggested workarounds.

Several web applications that previously relied on exporting HTML files as XLS have run into trouble as a result of the update - SalesForce is one example.

Answers from before July 12th 2016 to this and similar questions are likely to now be invalid.

It's worth noting that files produced ON THE BROWSER from remote data do not fall afoul of this protection; it only impedes files downloaded from a remote source that is not trusted. Therefore one possible approach is to generate the .XLS-labelled HTML file locally on the client.

Another, of course, is to produce a valid XLS file, which Excel will then open in Protected mode.

UPDATE: Microsoft has released a patch to correct this behavior: https://support.microsoft.com/en-us/kb/3181507


add this to your head:

<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

and add this as your javascript:

<script type="text/javascript">
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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></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))
  }
})()
</script>

Jfiddle: http://jsfiddle.net/cmewv/537/


SheetJS seems perfect for this.

To export your table as an excel file use the code in this link(along with SheetJS)

Just plug in your table element's id into export_table_to_excel

See Demo