Home » excel » javascript – HTML table export to Excel (XLS or CSV)

javascript – HTML table export to Excel (XLS or CSV)

Posted by: admin April 23, 2020 Leave a comment


I’m trying to export HTML table content to excel. I saw this solution which worked but not as I expected it (because I can’t choose which columns to copy, and it doesn’t works with big tables).

And another solution to copy by js and manually paste to excel file, which didn’t work as well, and I don’t really fancy this method.

Shortly what I want is, export customized view of the table, not all columns. to show you an example of what I mean:

Here is the normal table view:

enter image description here

and Here is how what I want to show in excel:

enter image description here

But because I have hidden fields, the first method didn’t work:

enter image description here

I would like a client side, cross-browser, workaround/solution, considering that I have around 2,500 lines in the table.

How to&Answers:

I made something very similar and use it every day in my office following a tutorial found on the web.
You can use this template for PHP:

   header ("Content-Type: application/vnd.ms-excel");
   header ("Content-Disposition: inline; filename=$filename");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang=it><head>
<table border="1">
for ($i=1;$i < 11; $i++)
   echo "<tr>";
   for ($j=1; $j<11;$j++)
      $a = $i * $j;
      echo "<td>$a</td>";
   echo "</tr>";

You can write something similar with JS, just generate a simple table with HTML tags and be sure to write the correct code in the header.


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.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
                            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

        <iframe id="txtArea1" style="display:none"></iframe>

    Call this function on

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