Export From HTML Table Using jQuery

Introduction

In this article we will see how to export from an HTML table using jQuery. We all work in some applications where we are playing with data’s . It might be some data returned by the server or it might be some client side data like HTML table. No matter which ever form the data is, there will be an export option. Isn’t it? 80% of our clients need the data to be exported as excel. So we need to give the option to export the given data to excel, not dependent of the data format. In my case my data is in the form of an HTML table, so in this post we will explain how to export an html data to excel, pdf, png, jpeg etc. I hope you will like it.

Download source code here : HTML Table Export

See this article in my website : here

Background

This article explains how to export a HTML table using jQuery. It covers exporting to the following formats:
  1. Excel
  2. PDF
  3. Image
  4. CSV
  5. PPT
  6. Word
  7. TXT
  8. XML

Why

In my project, we are doing 80% of our work in the client side. So I decided to implement the export feature in the client side itself. The same can be done using server-side code also but I prefer the client-side one.

What you must know

  1. jQuery
  2. JavaScript
  3. CSS 3
  4. HTML
  5. DOM Manipulations in jQuery

Using the code

Before you start, you need to download the necessary files from: TableExport.jquery.plugin.

Once you have download the files, you need to include those in your project. Here I am using a MVC4 web application.

  1. <script src="~/Contents/jquery-1.9.1.js"></script>  
  2. <script src="~/Contents/tableExport.js"></script> @*Main file which does export feature *@  
  3. <script src="~/Contents/jquery.base64.js"></script> @*Main file which does convert the content to base64  *@  
  4. <script src="~/Contents/html2canvas.js"></script> @*Main file which does export to image feature *@  
  5. <script src="~/Contents/jspdf/libs/base64.js"></script> @*Main file which does  convert the content to base64 for pdf *@  
  6. <script src="~/Contents/jspdf/libs/sprintf.js"></script> @*Main file which does export feature for pdf *@  
  7. <script src="~/Contents/jspdf/jspdf.js"></script> @*Main file which does export feature for pdf *@  
Let's say you have an HTML table as follows:
  1. <table id="activity" >  
  2.     <thead>              
  3.         <tr>  
  4.             <th>Name</th>  
  5.             <th>Activity on Code Project (%)</th>  
  6.             <th>Activity on C# Corner (%)</th>  
  7.             <th>Activity on Asp Forum (%)</th>  
  8.         </tr>  
  9.     </thead>  
  10.     <tbody>  
  11.         <tr>  
  12.             <td>Sibeesh</td>  
  13.             <td>100</td>  
  14.             <td>98</td>  
  15.             <td>80</td>  
  16.         </tr>  
  17.         <tr>  
  18.             <td>Ajay</td>  
  19.             <td>90</td>  
  20.             <td>0</td>  
  21.             <td>50</td>  
  22.         </tr>  
  23.         <tr>  
  24.             <td>Ansary</td>  
  25.             <td>100</td>  
  26.             <td>20</td>  
  27.             <td>10</td>  
  28.         </tr>  
  29.         <tr>  
  30.             <td>Aghil</td>  
  31.             <td>0</td>  
  32.             <td>30</td>  
  33.             <td>90</td>  
  34.         </tr>  
  35.         <tr>  
  36.             <td>Arya</td>  
  37.             <td>0</td>  
  38.             <td>0</td>  
  39.             <td>95</td>  
  40.         </tr>         
  41.     </tbody>  
  42. </table>  
Add some more UI elements for firing the click events.
    1. <table>  
    2.     <tr id="footerExport">  
    3.         <td id="exportexcel"><img src="~/icons/xls.png" title="Export to Excel" /></td>  
    4.         <td id="exportpdf"><img src="~/icons/pdf.png" title="Export to PDF" /></td>  
    5.         <td id="exportimage"><img src="~/icons/png.png" title="Export to PNG" /></td>  
    6.         <td id="exportcsv"><img src="~/icons/csv.png" title="Export to CSV" /></td>  
    7.         <td id="exportword"><img src="~/icons/word.png" title="Export to Word" /></td>  
    8.         <td id="exporttxt"><img src="~/icons/txt.png" title="Export to TXT" /></td>  
    9.         <td id="exportxml"><img src="~/icons/xml.png" title="Export to XML" /></td>  
    10.         <td id="exportppt"><img src="~/icons/ppt.png" title="Export to PPT" /></td>  
    11.     </tr>  
    12. </table> 
    Add a few styles to the table to make it viewable. 
      1. <style>  
      2.     #activity {  
      3.         text-align:center;border:1px solid #ccc;  
      4.     }  
      5.     #activity td{  
      6.         text-align:center;border:1px solid #ccc;  
      7.     }  
      8.      #footerExport td{  
      9.        cursor:pointer;  
      10.        text-align:center;border:1px solid #ccc;  
      11.        border:none;  
      12.     }  
      13.       
      14. </style> 
      Now it is time to fire our events :) You can do that as in the following.
        1. <script>  
        2.     $(document).ready(function () {  
        3.         $('#exportexcel').bind('click'function (e) {             
        4.             $('#activity').tableExport({ type: 'excel', escape: 'false' });  
        5.         });  
        6.         $('#exportpdf').bind('click'function (e) {             
        7.             $('#activity').tableExport({ type: 'pdf', escape: 'false' });  
        8.         });  
        9.         $('#exportimage').bind('click'function (e) {  
        10.             $('#activity').tableExport({ type: 'png', escape: 'false' });  
        11.         });  
        12.         $('#exportcsv').bind('click'function (e) {  
        13.             $('#activity').tableExport({ type: 'csv', escape: 'false' });  
        14.         });  
        15.         $('#exportppt').bind('click'function (e) {  
        16.             $('#activity').tableExport({ type: 'powerpoint', escape: 'false' });  
        17.         });  
        18.         $('#exportxml').bind('click'function (e) {  
        19.             $('#activity').tableExport({ type: 'xml', escape: 'false' });  
        20.         });  
        21.         $('#exportword').bind('click'function (e) {  
        22.             $('#activity').tableExport({ type: 'doc', escape: 'false' });  
        23.         });  
        24.         $('#exporttxt').bind('click'function (e) {  
        25.             $('#activity').tableExport({ type: 'txt', escape: 'false' });  
        26.         });  
        27.   
        28.     });  
        29. </script> 
        Please note that you can export to a few more formats in the same way. You can learn more here: tableExport.jquery.plugin.

        Explanation

        Now its time go deeper into that plugin. In the downloaded files you can see a file called tableExport.js. just open that file, you can see some conditions for specific formats. And the default property for exporting as follows.
        1. var defaults = {  
        2.                    separator: ',',  
        3.                    ignoreColumn: [],  
        4.                    tableName:'yourTableName',  
        5.                    type:'csv',  
        6.                    pdfFontSize:7,  
        7.                    pdfLeftMargin:20,  
        8.                    escape:'true',  
        9.                    htmlContent:'false',  
        10.                    consoleLog:'false'  
        11.                 };  
        You can change these properties depending on your needs as follows.
        1. var varpdfFontSize= '7';  
        2.   
        3. $('#activity').tableExport({ type: 'excel', escape: 'false',pdfFontSize:varpdfFontSize});  
        You can try all the properties listed above like this :).

        Now in that file you can see an if else if condition that is satisfied for multiple formats. Let me explain for Excel formatting alone.
        1. var excel="<table>";  
        2.                     // Header  
        3.                     $(el).find('thead').find('tr').each(function() {  
        4.                         excel += "<tr>";  
        5.                         $(this).filter(':visible').find('th').each(function(index,data) {  
        6.                             if ($(this).css('display') != 'none'){                      
        7.                                 if(defaults.ignoreColumn.indexOf(index) == -1){  
        8.                                     excel += "<td>" + parseString($(this))+ "</td>";  
        9.                                 }  
        10.                             }  
        11.                         });      
        12.                         excel += '</tr>';                          
        13.                           
        14.                     });                      
        15.                       
        16.                       
        17.                     // Row Vs Column  
        18.                     var rowCount=1;  
        19.                     $(el).find('tbody').find('tr').each(function() {  
        20.                         excel += "<tr>";  
        21.                         var colCount=0;  
        22.                         $(this).filter(':visible').find('td').each(function(index,data) {  
        23.                             if ($(this).css('display') != 'none'){      
        24.                                 if(defaults.ignoreColumn.indexOf(index) == -1){  
        25.                                     excel += "<td>"+parseString($(this))+"</td>";  
        26.                                 }  
        27.                             }  
        28.                             colCount++;  
        29.                         });                                                              
        30.                         rowCount++;  
        31.                         excel += '</tr>';  
        32.                     });                      
        33.                     excel += '</table>'  
        34.                       
        35.                     if(defaults.consoleLog == 'true'){  
        36.                         console.log(excel);  
        37.                     }  
        38.                       
        39.                     var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:"+defaults.type+"' xmlns='http://www.w3.org/TR/REC-html40'>";  
        40.                     excelFile += "<head>";  
        41.                     excelFile += "<!--[if gte mso 9]>";  
        42.                     excelFile += "<xml>";  
        43.                     excelFile += "<x:ExcelWorkbook>";  
        44.                     excelFile += "<x:ExcelWorksheets>";  
        45.                     excelFile += "<x:ExcelWorksheet>";  
        46.                     excelFile += "<x:Name>";  
        47.                     excelFile += "{worksheet}";  
        48.                     excelFile += "</x:Name>";  
        49.                     excelFile += "<x:WorksheetOptions>";  
        50.                     excelFile += "<x:DisplayGridlines/>";  
        51.                     excelFile += "</x:WorksheetOptions>";  
        52.                     excelFile += "</x:ExcelWorksheet>";  
        53.                     excelFile += "</x:ExcelWorksheets>";  
        54.                     excelFile += "</x:ExcelWorkbook>";  
        55.                     excelFile += "</xml>";  
        56.                     excelFile += "<![endif]-->";  
        57.                     excelFile += "</head>";  
        58.                     excelFile += "<body>";  
        59.                     excelFile += excel;  
        60.                     excelFile += "</body>";  
        61.                     excelFile += "</html>";  
        62.   
        63.                     var base64data = "base64," + $.base64.encode(excelFile);  
        64.                     window.open('data:application/vnd.ms-'+defaults.type+';filename=exportData.doc;' + base64data);  
        Procedure 
        1. Find the UI element (in this case it is our HTML table).

        2. Loop through the rows of the thread for the header information.

        3. Apply a filter to avoid the UI elements that has a display as none (filter(':visible')).

        4. If the UI is visible, append it to the variable (excel += "<td>" + parseString($(this))+ "</td>";)

          The same procedure is done for the row vs column values also. The only difference is, here we are looping through the tbody instead of thread.

        5. After the data is manipulated, data is formulated in the Excel format.
        You can learn more in the attachment.

        Output


        Points of Interest

        JQuesry, CSS, HTML, Export

        History

        • 1st version: 18-11-2014
        • 2nd Version : 24-11-2014

        Changes done

        1. Added Images to UI elements
        2. Added some export feature

        Please be noted that I have taken the images from plugin author's website (http://ngiriraj.com/pages/htmltable_export/demo.php) . You can find out more from that website.

        Conclusion

        Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

        Your turn. What do you think?

        A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.
        Kindest Regards
        Sibeesh Venu
         
         

        Up Next
          Ebook Download
          View all
          Learn
          View all