Javascript Export Html Table To CSV/XLS

Do you want to add quick table export feature into CSV, XLS format if yes then in this post I am going to share simple javascript script to export html table to excel. This is useful for adding quick excel export feature.

Javascript Export Html Table To Excel

HTML

<h1>Html table to excel or csv <small style="font-size:17px">---With export for IE and Edge</small></h1>
 
 Test1: <button id="btnExport" onclick="javascript:xport.toXLS('testTable');"> Export to XLS</button> <em>&nbsp;&nbsp;&nbsp;Export the table to XLS with CSV fallback for IE & Edge</em>
 
 
Test 2: <button id="btnExport" onclick="javascript:xport.toCSV('testTable');"> Export to CSV</button> <em>&nbsp;&nbsp;&nbsp;Export the table to CSV for all browsers</em>
 
 
 Test3: <button id="btnExport" onclick="javascript:xport.toXLS('testTable', 'outputdata');"> Export to XLS</button> <em>&nbsp;&nbsp;&nbsp;Export the table to XLS with custom filename</em>
 
<br />
 
<table id="testTable" summary="Code page support in different versions of MS Windows." rules="groups" frame="hsides" border="2" class="table table-striped">
  <caption>CODE-PAGE SUPPORT IN MICROSOFT WINDOWS</caption>
  <colgroup align="center"></colgroup>
  <colgroup align="left"></colgroup>
  <colgroup span="2" align="center"></colgroup>
  <colgroup span="3" align="center"></colgroup>
  <thead valign="top">
    <tr>
      <th>Code-Page<br>ID</th>
      <th>Name</th>
      <th>ACP</th>
      <th>OEMCP</th>
      <th>Windows<br>NT 3.1</th>
      <th>Windows<br>NT 3.51</th>
      <th>Windows<br>95</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1200</td>
      <td style="background-color: #00f; color: #fff">Windows 3.11</td>
      <td></td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>*</td>
    </tr>
    <tr>
      <td>1250</td>
      <td style="font-weight: bold">Windows 3.1 Eastern European</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1251</td>
      <td>Windows 3.1 Cyrillic</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1252</td>
      <td>Windows 3.1 US (ANSI)</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1253</td>
      <td>Windows 3.1 Greek</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1254</td>
      <td>Windows 3.1 Turkish</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1255</td>
      <td>Hebrew</td>
      <td>X</td>
      <td></td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>1256</td>
      <td>Arabic</td>
      <td>X</td>
      <td></td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>1257</td>
      <td>Baltic</td>
      <td>X</td>
      <td></td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>1361</td>
      <td>Korean (Johab)</td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>**</td>
      <td>X</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td>437</td>
      <td>MS-DOS United States</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>708</td>
      <td>Arabic (ASMO 708)</td>
      <td></td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>709</td>
      <td>Arabic (ASMO 449+, BCON V4)</td>
      <td></td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>710</td>
      <td>Arabic (Transparent Arabic)</td>
      <td></td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>720</td>
      <td>Arabic (Transparent ASMO)</td>
      <td></td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
  </tbody>
</table>


Javascript

var xport = {
  _fallbacktoCSV: true,  
  toXLS: function(tableId, filename) {   
    this._filename = (typeof filename == 'undefined') ? tableId : filename;
 
    //var ieVersion = this._getMsieVersion();
    //Fallback to CSV for IE & Edge
    if ((this._getMsieVersion() || this._isFirefox()) && this._fallbacktoCSV) {
      return this.toCSV(tableId);
    } else if (this._getMsieVersion() || this._isFirefox()) {
      alert("Not supported browser");
    }
 
    //Other Browser can download xls
    var htmltable = document.getElementById(tableId);
    var html = htmltable.outerHTML;
 
    this._downloadAnchor("data:application/vnd.ms-excel" + encodeURIComponent(html), 'xls'); 
  },
  toCSV: function(tableId, filename) {
    this._filename = (typeof filename === 'undefined') ? tableId : filename;
    // Generate our CSV string from out HTML Table
    var csv = this._tableToCSV(document.getElementById(tableId));
    // Create a CSV Blob
    var blob = new Blob([csv], { type: "text/csv" });
 
    // Determine which approach to take for the download
    if (navigator.msSaveOrOpenBlob) {
      // Works for Internet Explorer and Microsoft Edge
      navigator.msSaveOrOpenBlob(blob, this._filename + ".csv");
    } else {      
      this._downloadAnchor(URL.createObjectURL(blob), 'csv');      
    }
  },
  _getMsieVersion: function() {
    var ua = window.navigator.userAgent;
 
    var msie = ua.indexOf("MSIE ");
    if (msie > 0) {
      // IE 10 or older => return version number
      return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)), 10);
    }
 
    var trident = ua.indexOf("Trident/");
    if (trident > 0) {
      // IE 11 => return version number
      var rv = ua.indexOf("rv:");
      return parseInt(ua.substring(rv + 3, ua.indexOf(".", rv)), 10);
    }
 
    var edge = ua.indexOf("Edge/");
    if (edge > 0) {
      // Edge (IE 12+) => return version number
      return parseInt(ua.substring(edge + 5, ua.indexOf(".", edge)), 10);
    }
 
    // other browser
    return false;
  },
  _isFirefox: function(){
    if (navigator.userAgent.indexOf("Firefox") > 0) {
      return 1;
    }
 
    return 0;
  },
  _downloadAnchor: function(content, ext) {
      var anchor = document.createElement("a");
      anchor.style = "display:none !important";
      anchor.id = "downloadanchor";
      document.body.appendChild(anchor);
 
      // If the [download] attribute is supported, try to use it
 
      if ("download" in anchor) {
        anchor.download = this._filename + "." + ext;
      }
      anchor.href = content;
      anchor.click();
      anchor.remove();
  },
  _tableToCSV: function(table) {
    // We'll be co-opting `slice` to create arrays
    var slice = Array.prototype.slice;
 
    return slice
      .call(table.rows)
      .map(function(row) {
        return slice
          .call(row.cells)
          .map(function(cell) {
            return '"t"'.replace("t", cell.textContent);
          })
          .join(",");
      })
      .join("\r\n");
  }
};

See live demo and download source code.

DEMO | DOWNLOAD

This awesome script developed by kostas-krevatas. Visit their official repository for more information and follow for future updates.


Don’t forget to Subscribe My Public Notebook for more useful free scripts, tutorials and articles.

One Reply to “Javascript Export Html Table To CSV/XLS”

  1. Hi, this above code is working only hardcode data but I am using input filed inside .

    this is not working please provide salutions.

    Thanks.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.