[javascript] How to export html table to excel using javascript

My table is in format

<table id="mytable">
<thead>
  <tr>
    <th>name</th>
    <th>place</th>
  </tr>
</thead>
<tbody>
<tr>
   <td>adfas</td>
   <td>asdfasf</td>
</tr>
</tbody>
</table>

I found the following code online. But it doesn't work if i use "thead" and "tbody" tags

function write_to_excel() {

    str = "";

    var mytable = document.getElementsByTagName("table")[0];
    var rowCount = mytable.rows.length;
    var colCount = mytable.getElementsByTagName("tr")[0].getElementsByTagName("td").length;

    var ExcelApp = new ActiveXObject("Excel.Application");
    var ExcelSheet = new ActiveXObject("Excel.Sheet");
    ExcelSheet.Application.Visible = true;

    for (var i = 0; i < rowCount; i++) {
        for (var j = 0; j < colCount; j++) {
            str = mytable.getElementsByTagName("tr")[i].getElementsByTagName("td")[j].innerHTML;
            ExcelSheet.ActiveSheet.Cells(i + 1, j + 1).Value = str;
        }
    }

This question is related to javascript html

The answer is


I think you can also think of alternative architectures. Sometimes something can be done in another way much more easier. If the producer of HTML file is you, then you can write an HTTP handler to create an Excel document on the server (which is much more easier than in JavaScript) and send a file to the client. If you receive that HTML file from somewhere (like an HTML version of a report), then you still can use a server side language like C# or PHP to create the Excel file still very easily. I mean, you may have other ways too. :)


I try this with jquery; use this and have fun :D

    jQuery.printInExcel = function (DivID) 
{ 
var ExcelApp = new ActiveXObject("Excel.Application"); 
ExcelApp.Workbooks.Add; 
ExcelApp.visible = true; 
var str = ""; 
var tblcount = 0; 
var trcount = 0;
 $("#" + DivID + " table").each(function () 
{ $(this).find("tr").each(function () 
{ var tdcount = 0; $(this).find("td").each(function () 
{ str = str + $(this).text(); ExcelApp.Cells(trcount + 1, tdcount + 1).Value = str; 
str = ""; tdcount++ 
}); 
trcount++ 
}); tblcount++ 
}); 
};

use this in your class and call it with $.printInExcel(your var);


Check this out... I just got this working and it seems exactly what you are trying to do as well.

2 functions. One to select the table and copy it to the clipboard, and the second writes it to excel en masse. Just call write_to_excel() and put in your table id (or modify it to take it as an argument).

  function selectElementContents(el) {
        var body = document.body, range, sel;
        if (document.createRange && window.getSelection) {
            range = document.createRange();
            sel = window.getSelection();
            sel.removeAllRanges();
            try {
                range.selectNodeContents(el);
                sel.addRange(range);
            } catch (e) {
                range.selectNode(el);
                sel.addRange(range);
            }
        } else if (body.createTextRange) {
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
        }
        range.execCommand("Copy");
    }

function write_to_excel() 
{
var tableID = "AllItems";
selectElementContents( document.getElementById(tableID) );

var excel = new ActiveXObject("Excel.Application");
// excel.Application.Visible = true; 
var wb=excel.WorkBooks.Add();
var ws=wb.Sheets("Sheet1");
ws.Cells(1,1).Select;
ws.Paste;
ws.DrawingObjects.Delete;
ws.Range("A1").Select
 excel.Application.Visible = true; 
}

Heavily influenced from: Select a complete table with Javascript (to be copied to clipboard)


Only works in Mozilla, Chrome and Safari..

_x000D_
_x000D_
$(function() {
  $('button').click(function() {
    var url = 'data:application/vnd.ms-excel,' + encodeURIComponent($('#tableWrap').html())
    location.href = url
    return false
  })
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

</script>
<button>click me</button>
<div id="tableWrap">
  <table>
    <thead>
      <tr>
        <th>A</th>
        <th>B</th>
        <th>C</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
      </tr>
    </tbody>
  </table>
</div>
_x000D_
_x000D_
_x000D_


    function XLExport() {
        try {
            var i;
            var j;
            var mycell;
            var tableID = "tblInnerHTML";

            var objXL = new ActiveXObject("Excel.Application");
            var objWB = objXL.Workbooks.Add();
            var objWS = objWB.ActiveSheet;

            for (i = 0; i < document.getElementById('<%= tblAuditReport.ClientID %>').rows.length; i++) {
                for (j = 0; j < document.getElementById('<%= tblAuditReport.ClientID %>').rows(i).cells.length; j++) {
                    mycell = document.getElementById('<%= tblAuditReport.ClientID %>').rows(i).cells(j);
                    objWS.Cells(i + 1, j + 1).Value = mycell.innerText;
                }
            }

            //objWS.Range("A1", "L1").Font.Bold = true;

            objWS.Range("A1", "Z1").EntireColumn.AutoFit();

            //objWS.Range("C1", "C1").ColumnWidth = 50;

            objXL.Visible = true;

        }
        catch (err) {
                    }

    }

Check https://github.com/linways/table-to-excel. Its a wrapper for exceljs/exceljs to export html tables to xlsx.

_x000D_
_x000D_
TableToExcel.convert(document.getElementById("simpleTable1"));
_x000D_
<script src="https://cdn.jsdelivr.net/gh/linways/[email protected]/dist/tableToExcel.js"></script>_x000D_
<table id="simpleTable1" data-cols-width="70,15,10">_x000D_
<tbody>_x000D_
    <tr>_x000D_
        <td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="middle" data-f-underline="true">_x000D_
            Sample Excel_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial" data-a-v="top">_x000D_
            Italic and horizontal center in Arial_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <th data-a-text-rotation="90">Col 1 (number)</th>_x000D_
        <th data-a-text-rotation="vertical">Col 2</th>_x000D_
        <th data-a-wrap="true">Wrapped Text</th>_x000D_
        <th data-a-text-rotation="-45">Col 4 (date)</th>_x000D_
        <th data-a-text-rotation="-90">Col 5</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td rowspan="1" data-t="n">1</td>_x000D_
        <td rowspan="1" data-b-b-s="thick" data-b-l-s="thick" data-b-r-s="thick">_x000D_
            ABC1_x000D_
        </td>_x000D_
        <td rowspan="1" data-f-strike="true">Striked Text</td>_x000D_
        <td data-t="d">05-20-2018</td>_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2210.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td rowspan="2" data-t="n">2</td>_x000D_
        <td rowspan="2" data-fill-color="FFFF0000" data-f-color="FFFFFFFF">_x000D_
            ABC 2_x000D_
        </td>_x000D_
        <td rowspan="2" data-a-indent="3">Merged cell</td>_x000D_
        <td data-t="d">05-21-2018</td>_x000D_
        <td data-t="n" data-b-a-s="dashed" data-num-fmt="$ 0.00">230.00</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="d">05-22-2018</td>_x000D_
_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2493.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-h="right" data-hyperlink="https://google.com">_x000D_
            <b><a href="https://google.com">Hyperlink</a></b>_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>4933.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-rtl="true">_x000D_
            ?????_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>2009.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-a-s="dashed" data-b-a-c="FFFF0000">All borders</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="b">true</td>_x000D_
        <td data-t="b">false</td>_x000D_
        <td data-t="b">1</td>_x000D_
        <td data-t="b">0</td>_x000D_
        <td data-error="#VALUE!">Value Error</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-t-s="thick" data-b-l-s="thick" data-b-b-s="thick" data-b-r-s="thick" data-b-t-c="FF00FF00" data-b-l-c="FF00FF00" data-b-b-c="FF00FF00" data-b-r-c="FF00FF00">_x000D_
            All borders separately_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr data-exclude="true">_x000D_
        <td>Excluded row</td>_x000D_
        <td>Something</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Included Cell</td>_x000D_
        <td data-exclude="true">Excluded Cell</td>_x000D_
        <td>Included Cell</td>_x000D_
    </tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This creates valid xlsx on the client side. Also supports some basic styling. Check https://codepen.io/rohithb/pen/YdjVbb for a working example.


This might be a better answer copied from this question. Please try it and give opinion here. Please vote up if found useful. Thank you.

<script type="text/javascript">
function generate_excel(tableid) {
  var table= document.getElementById(tableid);
  var html = table.outerHTML;
  window.open('data:application/vnd.ms-excel;base64,' + base64_encode(html));
}

function base64_encode (data) {
  // http://kevin.vanzonneveld.net
  // +   original by: Tyler Akins (http://rumkin.com)
  // +   improved by: Bayron Guevara
  // +   improved by: Thunder.m
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Pellentesque Malesuada
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Rafal Kukawski (http://kukawski.pl)
  // *     example 1: base64_encode('Kevin van Zonneveld');
  // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  // mozilla has this native
  // - but breaks in 2.0.0.12!
  //if (typeof this.window['btoa'] == 'function') {
  //    return btoa(data);
  //}
  var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = "",
    tmp_arr = [];

  if (!data) {
    return data;
  }

  do { // pack three octets into four hexets
    o1 = data.charCodeAt(i++);
    o2 = data.charCodeAt(i++);
    o3 = data.charCodeAt(i++);

    bits = o1 << 16 | o2 << 8 | o3;

    h1 = bits >> 18 & 0x3f;
    h2 = bits >> 12 & 0x3f;
    h3 = bits >> 6 & 0x3f;
    h4 = bits & 0x3f;

    // use hexets to index into b64, and append result to encoded string
    tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  } while (i < data.length);

  enc = tmp_arr.join('');

  var r = data.length % 3;

  return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

}
</script>

I would suggest using a different approach. Add a button on the webpage that will copy the content of the table to the clipboard, with TAB chars between columns and newlines between rows. This way the "paste" function in Excel should work correctly and your web application will also work with many browsers and on many operating systems (linux, mac, mobile) and users will be able to use the data also with other spreadsheets or word processing programs.

The only tricky part is to copy to the clipboard because many browsers are security obsessed on this. A solution is to prepare the data already selected in a textarea, and show it to the user in a modal dialog box where you tell the user to copy the text (some will need to type Ctrl-C, others Command-c, others will use a "long touch" or a popup menu).

It would be nicer to have a standard copy-to-clipboard function that possibly requests a user confirmation... but this is not the case, unfortunately.


Excel Export Script works on IE7+ , Firefox and Chrome
===========================================================



function fnExcelReport()
    {
             var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
             var textRange; var j=0;
          tab = document.getElementById('headerTable'); // id of 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 u want links in your table
          tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
                      tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves 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,"Say Thanks to Sumit.xls");
                          }  
                  else                 //other browser not tested on IE 11
                      sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  


                      return (sa);
                            }

    Just Create a blank iframe
    enter code here
        <iframe id="txtArea1" style="display:none"></iframe>

    Call this function on

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