Export table to excel with jquery

tableExport.jquery.plugin

Export HTML Table to

  • CSV
  • DOC
  • JSON
  • PDF
  • PNG
  • SQL
  • TSV
  • TXT
  • XLS (Excel 2000 HTML format)
  • XLSX (Excel 2007 Office Open XML format)
  • XML (Excel 2003 XML Spreadsheet format)
  • XML (Raw xml)

Installation

To save the generated export files on client side, include in your html code:

<script type="text/javascript" src="libs/FileSaver/FileSaver.min.js"></script>

To export the table in XLSX (Excel 2007+ XML Format) format, you need to include additionally SheetJS/js-xlsx:

<script type="text/javascript" src="libs/js-xlsx/xlsx.core.min.js"></script>

In case you still want to support IE11, you need to include jsPDF’s polyfills.umd.js.
Please do this before you include jspdf.umd.min.js and html2canvas.min.js

<script type="text/javascript" src="../libs/jsPDF/polyfills.umd.js"></script>

To export an html table to a PDF file, you can use jsPDF as a PDF producer:

<script type="text/javascript" src="libs/jsPDF/jspdf.umd.min.js"></script>

Many HTML stylings can be converted to PDF with jsPDF, but support for non-western character sets is almost non-existent. Especially if you want to export Arabic or Chinese characters to your PDF file, you can use pdfmake as an alternative PDF producer. The disadvantage compared to jspdf is that using pdfmake has a reduced styling capability. To use pdfmake enable the pdfmake option and instead of the jsPDF files include

<script type="text/javascript" src="libs/pdfmake/pdfmake.min.js"></script>
<script type="text/javascript" src="libs/pdfmake/vfs_fonts.js"></script>

<!-- To export arabic characters include mirza_fonts.js _instead_ of vfs_fonts.js
<script type="text/javascript" src="libs/pdfmake/mirza_fonts.js"></script>
-->

<!-- For a chinese font include either gbsn00lp_fonts.js or ZCOOLXiaoWei_fonts.js _instead_ of vfs_fonts.js 
<script type="text/javascript" src="libs/pdfmake/gbsn00lp_fonts.js"></script>
-->

To export the table in PNG format, you need to include:

<script type="text/javascript" src="libs/html2canvas/html2canvas.min.js"></script>

Regardless of the desired format, finally include:

<script type="text/javascript" src="tableExport.min.js"></script>

Please keep this include order.

Dependencies

Library Version
jQuery >= 3.2.1
FileSaver >= 2.0.1
html2canvas >= 1.0.0
jsPDF >=2.0.0
pdfmake 0.1.71
SheetJS >= 0.16.0

Examples

// CSV format

$('#tableID').tableExport({type:'csv'});
// Excel 2000 html format

$('#tableID').tableExport({type:'excel'});
// XML Spreadsheet 2003 file format with multiple worksheet support

$('table').tableExport({type:'excel',
                        mso: {fileFormat:'xmlss',
                              worksheetName: ['Table 1','Table 2', 'Table 3']}});
// PDF export using jsPDF only

$('#tableID').tableExport({type:'pdf',
                           jspdf: {orientation: 'p',
                                   margins: {left:20, top:10},
                                   autotable: false}
                          });
// PDF format using jsPDF and jsPDF Autotable 

$('#tableID').tableExport({type:'pdf',
                           jspdf: {orientation: 'l',
                                   format: 'a3',
                                   margins: {left:10, right:10, top:20, bottom:20},
                                   autotable: {styles: {fillColor: 'inherit', 
                                                        textColor: 'inherit'},
                                               tableWidth: 'auto'}
                                  }
                          });
// PDF format with callback example

function DoCellData(cell, row, col, data) {}
function DoBeforeAutotable(table, headers, rows, AutotableSettings) {}

$('table').tableExport({fileName: sFileName,
                        type: 'pdf',
                        jspdf: {format: 'bestfit',
                                margins: {left:20, right:10, top:20, bottom:20},
                                autotable: {styles: {overflow: 'linebreak'},
                                            tableWidth: 'wrap',
                                            tableExport: {onBeforeAutotable: DoBeforeAutotable,
                                                          onCellData: DoCellData}}}
                       });
// PDF export using pdfmake

$('#tableID').tableExport({type:'pdf',
                           pdfmake:{enabled:true,
                                    docDefinition:{pageOrientation:'landscape'}}
                          });

Options (Default settings)

csvEnclosure: '"'
csvSeparator: ','
csvUseBOM: true
date: html: 'dd/mm/yyyy'
exportHiddenCells: false
fileName: 'tableExport'
htmlContent: false
htmlHyperlink: 'content'
ignoreColumn: []
ignoreRow: []
jsonScope: 'all'
jspdf: orientation: 'p'
       unit:'pt'
       format: 'a4'
       margins: left: 20
                right: 10
                top: 10
                bottom: 10
       onDocCreated: null
       autotable: styles: cellPadding: 2
                          rowHeight: 12
                          fontSize: 8
                          fillColor: 255
                          textColor: 50
                          fontStyle: 'normal'
                          overflow: 'ellipsize'
                          halign: 'inherit'
                          valign: 'middle'
                  headerStyles: fillColor: [52, 73, 94]
                                textColor: 255
                                fontStyle: 'bold'
                                halign: 'inherit'
                                valign: 'middle'
                  alternateRowStyles: fillColor: 245
                  tableExport: doc: null
                               onAfterAutotable: null
                               onBeforeAutotable: null
                               onAutotableText: null
                               onTable: null
                               outputImages: true
mso: fileFormat: 'xlshtml'
     onMsoNumberFormat: null
     pageFormat: 'a4'
     pageOrientation: 'portrait'
     rtl: false
     styles: []
     worksheetName: ''
     xlsx: formatId: date: 14
                     numbers: 2
                     currency: 164
           format: currency: '$#,##0.00;[Red]-$#,##0.00'
           onHyperlink: null
numbers: html: decimalMark: '.'
               thousandsSeparator: ','
         output: decimalMark: '.'
                 thousandsSeparator: ','
onAfterSaveToFile: null
onBeforeSaveToFile: null
onCellData: null
onCellHtmlData: null
onCellHtmlHyperlink: null
onIgnoreRow: null
onTableExportBegin: null
onTableExportEnd: null
outputMode: 'file'
pdfmake: enabled: false
         docDefinition: pageSize: 'A4'
                        pageOrientation: 'portrait'
                        styles: header: background: '#34495E'
                                        color: '#FFFFFF'
                                        bold: true
                                        alignment: 'center'
                                        fillColor: '#34495E'
                        alternateRow: fillColor: '#f5f5f5'
                        defaultStyle: color: '#000000'
                                      fontSize: 8
                                      font: 'Roboto'
         fonts: {}
preserve: leadingWS: false
          trailingWS: false
preventInjection: true
sql: tableEnclosure:  '`'
     columnEnclosure: '`' 
tbodySelector: 'tr'
tfootSelector: 'tr'
theadSelector: 'tr'
tableName: 'myTableName'
type: 'csv'

Notes on options that apply to all formats

The option ignoreColumn can be either an array of indexes (i.e. [0, 2]) or field names (i.e. [«id», «name»]), where

  • Indexes correspond to the position of the header elements th in the DOM starting at 0. (If the th elements are removed or added to the DOM, the indexes will be shifted so use the functionality wisely!)
  • Field names should correspond to the values set on the «data-field» attribute of the header elements th in the DOM.
  • «Nameless» columns without data-field attribute will be named by their index number (converted to a string)

To disable formatting of numbers in the exported output, which can be useful for csv and excel format, set the option numbers: output to false.

There is an option preventInjection (enabled by default) that prevents the injection of formulas when exporting in CSV or Excel format. To achieve this, a single quote is appended to cell strings starting with =,+,- or @

There are a couple of format-independent and format-specific callback functions that can be used to control the output result during export. All callback functions have a name starting with on and are initialized with null.

Notes for Excel formats

Set the option mso.fileFormat to 'xmlss' if you want to export in XML Spreadsheet 2003 file format. Use this format if multiple tables should be exported into a single file.

Excel 2000 html format is the default excel file format which has better support of exporting table styles.

The mso.styles option lets you define the css attributes of the original html table cells, that should be taken over when exporting to an excel worksheet (Excel 2000 html format only).

To export in XSLX format SheetJS/js-xlsx is used. Please note that with this format the amount of exportable styling information of the HTML table is limited compared to other formats.

When exporting in Excel 2000 html format (xlshtml), the default extension of the output file is XLS, although the type of the file content is HTML. When you open a file in Microsoft Office Excel 2007 or later that contains content that does not match the extensionof the file, you receive the following warning message:
The file you are trying to open, 'name.ext', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?
According to a Knowledge base article the warning message can help prevent unexpected problems that might occur because of possible incompatibility between the actual content of the file and the file name extension. The article also gives you some hints to disable the warning message.

PDF format related options

For jsPDF options see the documentation of jsPDF. To generate tables with jsPDF this plugin uses a specific modified version (2.0.17) of jsPDF-AutoTable. Due to compatibility reasons the source code of this version has been integrated and was adapted.

There is an extended setting for the jsPDF option format. If you set the value of the option to bestfit, the tableExport plugin will try to choose the minimum required paper size and orientation in which the table (or tables in multitable mode) can be displayed without column adjustment.

Also there is an extended setting for the jsPDF-AutoTable options 'fillColor', 'textColor' and 'fontStyle'. When setting these option values to 'inherit' the original css values for background and text color will be used as fill and text color while exporting to pdf. A css font-weight >= 700 results in a bold fontStyle and the italic css font-style will be used as italic fontStyle.

When exporting to pdf the option outputImages lets you enable or disable the output of images that are located in the original html table.

Optional html data attributes

(can be applied while generating the table that you want to export)

data-tableexport-cellformat

<td data-tableexport-cellformat="">...</td> -> An empty data value preserves format of cell content. E.g. no number seperator conversion
                                               
                                               More cell formats to be come...

data-tableexport-colspan

<td colspan="2" data-tableexport-colspan="3">...</td> -> Overwrites the colspan attribute of the table cell during export. 
                                                         This attribute can be used if there follow hidden cells, that will be exported by using the "data-tableexport-display" attribute.

data-tableexport-display

<table style="display:none;" data-tableexport-display="always">...</table> -> A hidden table will be exported

<td style="display:none;" data-tableexport-display="always">...</td> -> A hidden cell will be exported

<td data-tableexport-display="none">...</td> -> This cell will not be exported

<tr data-tableexport-display="none">...</tr> -> All cells of this row will not be exported

data-tableexport-msonumberformat

<td data-tableexport-msonumberformat="@">...</td> -> Data value will be used to style excel cells with mso-number-format (Excel 2000 html format only)
                                                      Format                      Description
                                                      ===================================================================================
                                                      "@"                        Excel treats cell content always as text, even numbers
                                                      "0"                         Excel will display no decimals for numbers
                                                      "0.000"                    Excel displays numbers with 3 decimals
                                                      "0%"                        Excel will display a number as percent with no decimals
                                                      "Percent"                   Excel will display a number as percent with 2 decimals
                                                      "#,##0.000"            Comma with 3 decimals
                                                      "mm/dd/yy"                Date7
                                                      "mmmm d, yyyy"           Date9
                                                      "m/d/yy h:mm AM/PM"   D -T AMPM
                                                      "Short Date"                01/03/1998
                                                      "Medium Date"               01-mar-98
                                                      "d-mmm-yyyy"              01-mar-1998
                                                      "Short Time"                5:16
                                                      "Medium Time"               5:16 am
                                                      "Long Time"                 5:16:21:00
                                                      "0.E+00"                   Scientific Notation
                                                      "# ???/???"              Fractions - up to 3 digits
                                                      "022£022#,##0.00"  £12.76
                                                      "#,##0.00_ ;[Red]-#,##0.00 "  2 decimals, negative red numbers

data-tableexport-rowspan

<td rowspan="2" data-tableexport-rowspan="3">...</td> -> Overwrites the rowspan attribute of the table cell during export. 
                                                         This attribute can be used if there follow hidden rows, that will be exported by using the "data-tableexport-display" attribute.

data-tableexport-value

<th data-tableexport-value="export title">title</th> -> "export title" instead of "title" will be exported

<td data-tableexport-value="export content">content</td> -> "export content" instead of "content" will be exported

data-tableexport-xlsxformatid

<td data-tableexport-xlsxformatid="14">...</td> -> The data value represents a format id that will be used to format the content of a cell in Excel. This data attribute overwrites the default setting of defaults.mso.xslx.formatId. 
                                                   This attribute is for Excel 2007 Office Open XML format only.
                                                   
                                                   Format id                    Description
                                                   ===============================================================
                                                   "1"                          0
                                                   "2"                          0.00
                                                   "3"                          #,##0
                                                   "4"                          #,##0.00
                                                   "9"                          0%
                                                   "10"                         0.00%
                                                   "11"                         0.00E+00
                                                   "12"                         # ?/?
                                                   "13"                         # ??/??
                                                   "14"                         m/d/yy (will be localized by Excel)
                                                   "15"                         d-mmm-yy
                                                   "16"                         d-mmm
                                                   "17"                         mmm-yy
                                                   "18"                         h:mm AM/PM
                                                   "19"                         h:mm:ss AM/PM
                                                   "20"                         h:mm
                                                   "21"                         h:mm:ss
                                                   "22"                         m/d/yy h:mm
                                                   "37"                         #,##0 ;(#,##0)
                                                   "38"                         #,##0 ;[Red](#,##0)
                                                   "39"                         #,##0.00;(#,##0.00)
                                                   "40"                         #,##0.00;[Red](#,##0.00)
                                                   "45"                         mm:ss
                                                   "46"                         [h]:mm:ss
                                                   "47"                         mmss.0
                                                   "48"                         ##0.0E+0
                                                   "49"                         @
                                                   "56"                         上午/下午 hh時mm分ss秒
                                                   {mso.xlsx.formatid.currency} {mso.xlsx.format.currency}

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Any HTML table that you have created can be converted into an Excel Spreadsheet by using jQuery and it is compatible with all browsers. There are two simple approaches that require basic HTML and jQuery knowledge to achieve this.

    • Approach 1: Using jQuery plugin: A simple jQuery plugin ‘table2excel’ can be used for converting an HTML table to an excel sheet. 

    Syntax:

    $("#table-id").table2excel({
        filename: "excel_sheet-name.xls"
    });
    • Example: 

    html

    <table id="studtable">

        <tr>

            <th>ID</th>

            <th>Name</th>

            <th>Age</th>

            <th>Address</th>

        </tr>

        <tr>

            <td>101</td>

            <td>Alex</td>

            <td>15</td>

            <td>Maldives</td>

        </tr>

        <tr>

            <td>102</td>

            <td>Chris</td>

            <td>14</td>

            <td>Canada</td>

        </tr>

        <tr>

            <td>103</td>

            <td>Jay</td>

            <td>15</td>

            <td>Toronto</td>

        </tr>

    </table>

    <script>

     $(document).ready(function () {

        $("#studtable").table2excel({

            filename: "Students.xls"

        });

     });

    </script>

    • Output:
     
    ID    Name    Age    Address
    101    Alex    15    Maldives
    102    Chris    14    Canada
    103    Jay    15    Toronto
    • The above output gets converted into an Excel spreadsheet in the exact same manner the HTML table is. About ‘table2excel’: The ‘table2excel’ is a simple yet useful jQuery plugin that allows for exporting HTML table data to an Excel file. The ‘table2excel’ also has a feature to exclude cells that contain a specified class. Syntax for noExport:
    $(document).ready(function() {
        $("#table-id").table2excel({
            exclude: ".noExport",
            filename: "name-of-the-file",
        });
    });
    • Example code for excluding some specified cells: 

    html

    <script src=

    "//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">

    </script>

    <script src=

    "//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js">

    </script>

    <button>Export</button>

    <table>

        <thead>

            <tr>

                <td class="noExport">

                    This cell will not be exported.

                </td>

                <td>

                    This cell will get exported.

                </td>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td>Alex</td>

                <td class="noExport">Maldives</td>

            </tr>

            <tr>

                <td>Chris</td>

                <td>Canada</td>

            </tr>

        </tbody>

    </table>

    • Note: In the above sample code, the class ‘.noExport’ has been used to exclude those specified cells from the HTML table data. Therefore the exported Excel Spreadsheet also does not include those cells from the HTML table data.
    • Approach 2: Using simple HTML: Consider the same students table above to understand the below. Let’s use a button in our code which when clicked to converts the HTML data table into an Excel spreadsheet. Note that the ‘export’ button below does not actually convert the HTML table to an excel sheet. This has to used in a proper and already existing HTML code to get the Excel spreadsheet and will not work in this IDE. 

    html

    <!DOCTYPE html>

    <html>

    <head>

        <title>

            HTML Table To Excel

            spreadsheet using

            HTML only

        </title>

    </head>

    <body>

        <table id="studtable">

            <tr>

                <th>ID</th>

                <th>Name</th>

                <th>Age</th>

                <th>Address</th>

            </tr>

            <tr>

                <td>101</td>

                <td>Alex</td>

                <td>15</td>

                <td>Maldives</td>

            </tr>

            <tr>

                <td>102</td>

                <td>Chris</td>

                <td>14</td>

                <td>Canada</td>

            </tr>

            <tr>

                <td>103</td>

                <td>Jay</td>

                <td>15</td>

                <td>Toronto</td>

            </tr>

        </table>

        <button onclick="tableToExcel(

            'studtable', 'Students')">

            Click to Export

        </button>

    </body>

    </html>

    • Output:

     

    HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps. jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more“. 

    • HTML Tutorial and HTML Examples.
    • jQuery Tutorial and jQuery Examples.

    Like Article

    Save Article

    The reason the solution you found on the internet is no working is because of the line that starts var colCount. The variable mytable only has two elements being <thead> and <tbody>. The var colCount line is looking for all the elements within mytable that are <tr>. The best thing you can do is give an id to your <thead> and <tbody> and then grab all the values based on that. Say you had <thead id='headers'> :

    function write_headers_to_excel() 
    {
      str="";
    
      var myTableHead = document.getElementById('headers');
      var rowCount = myTableHead.rows.length;
      var colCount = myTableHead.getElementsByTagName("tr")[0].getElementsByTagName("th").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= myTableHead.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
            ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
        }
    }
    
    }
    

    and then do the same thing for the <tbody> tag.

    EDIT: I would also highly recommend using jQuery. It would shorten this up to:

    function write_to_excel() 
    {
     var ExcelApp = new ActiveXObject("Excel.Application");
     var ExcelSheet = new ActiveXObject("Excel.Sheet");
     ExcelSheet.Application.Visible = true; 
    
      $('th, td').each(function(i){
        ExcelSheet.ActiveSheet.Cells(i+1,i+1).Value = this.innerHTML;
      });
    }
    

    Now, of course, this is going to give you some formatting issues but you can work out how you want it formatted in Excel.

    EDIT: To answer your question about how to do this for n number of tables, the jQuery will do this already. To do it in raw Javascript, grab all the tables and then alter the function to be able to pass in the table as a parameter. For instance:

    var tables = document.getElementsByTagName('table');
    for(var i = 0; i < tables.length; i++)
    {
      write_headers_to_excel(tables[i]);
      write_bodies_to_excel(tables[i]);
    }
    

    Then change the function write_headers_to_excel() to function write_headers_to_excel(table). Then change var myTableHead = document.getElementById('headers'); to var myTableHead = table.getElementsByTagName('thead')[0];. Same with your write_bodies_to_excel() or however you want to set that up.

    Introduction

    This example shows how to export an HTML table to an Excel sheet using jquery table2excel plugin. 

    What is table2excel?

    table2excel is a jQuery Plugin. it is used to export HTML tables to Excel sheets. 

    How to Include table2excel jQuery Plugin Within HTML File 

    1. <script type=«text/javascript» src=«https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js»></script>  
    2. <script src=«table2excel.js» type=«text/javascript»></script>    

    table2excel.js Markup

    Create one text document within the root directory of your project and save that document with name  table2excel.js 

    After this, write the following code in table2excel.js file and save it.

    1.   
    2. ;  
    3. (function($, window, document, undefined) {  
    4.  var pluginName = «table2excel»
    5.   defaults = {  
    6.    exclude: «.noExl»,  
    7.    name: «Table2Excel»,  
    8.    filename: «table2excel»,  
    9.    fileext: «.xls»,  
    10.    exclude_img: true,  
    11.    exclude_links: true,  
    12.    exclude_inputs: true  
    13.   };  
    14.    
    15.  function Plugin(element, options) {  
    16.   this.element = element;  
    17.     
    18.     
    19.     
    20.     
    21.     
    22.   this.settings = $.extend({}, defaults, options);  
    23.   this._defaults = defaults;  
    24.   this._name = pluginName;  
    25.   this.init();  
    26.  }  
    27.  Plugin.prototype = {  
    28.   init: function() {  
    29.    var e = this;  
    30.    var utf8Heading = «<meta http-equiv=»content-type» content=»application/vnd.ms-excel; charset=UTF-8″>»;  
    31.    e.template = {  
    32.     head: «<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″>» + utf8Heading + «<head><!—[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>»,  
    33.     sheet: {  
    34.      head: «<x:ExcelWorksheet><x:Name>»,  
    35.      tail: «</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>»  
    36.     },  
    37.     mid: «</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]—></head><body>»,  
    38.     table: {  
    39.      head: «<table>»,  
    40.      tail: «</table>»  
    41.     },  
    42.     foot: «</body></html>»  
    43.    };  
    44.    e.tableRows = [];  
    45.      
    46.    $(e.element).each(function(i, o) {  
    47.     var tempRows = «»;  
    48.     $(o).find(«tr»).not(e.settings.exclude).each(function(i, p) {  
    49.      tempRows += «<tr>»;  
    50.      $(p).find(«td,th»).not(e.settings.exclude).each(function(i, q) {   
    51.       var rc = {  
    52.        rows: $(this).attr(«rowspan»),  
    53.        cols: $(this).attr(«colspan»),  
    54.        flag: $(q).find(e.settings.exclude)  
    55.       };  
    56.       if (rc.flag.length > 0) {  
    57.        tempRows += «<td> </td>»  
    58.       } else {  
    59.        if (rc.rows & rc.cols) {  
    60.         tempRows += «<td>» + $(q).html() + «</td>»;  
    61.        } else {  
    62.         tempRows += «<td»;  
    63.         if (rc.rows > 0) {  
    64.          tempRows += » rowspan='» + rc.rows + «‘ «;  
    65.         }  
    66.         if (rc.cols > 0) {  
    67.          tempRows += » colspan='» + rc.cols + «‘ «;  
    68.         }  
    69.         tempRows += «/>» + $(q).html() + «</td>»;  
    70.        }  
    71.       }  
    72.      });  
    73.      tempRows += «</tr>»;  
    74.      console.log(tempRows);  
    75.     });  
    76.       
    77.     if (e.settings.exclude_img) {  
    78.      tempRows = exclude_img(tempRows);  
    79.     }  
    80.       
    81.     if (e.settings.exclude_links) {  
    82.      tempRows = exclude_links(tempRows);  
    83.     }  
    84.       
    85.     if (e.settings.exclude_inputs) {  
    86.      tempRows = exclude_inputs(tempRows);  
    87.     }  
    88.     e.tableRows.push(tempRows);  
    89.    });  
    90.    e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName);  
    91.   },  
    92.   tableToExcel: function(table, name, sheetName) {  
    93.    var e = this,  
    94.     fullTemplate = «»,  
    95.     i, link, a;  
    96.    e.format = function(s, c) {  
    97.     return s.replace(/{(w+)}/g, function(m, p) {  
    98.      return c[p];  
    99.     });  
    100.    };  
    101.    sheetName = typeof sheetName === «undefined» ? «Sheet» : sheetName;  
    102.    e.ctx = {  
    103.     worksheet: name || «Worksheet»,  
    104.     table: table,  
    105.     sheetName: sheetName  
    106.    };  
    107.    fullTemplate = e.template.head;  
    108.    if ($.isArray(table)) {  
    109.     for (i in table) {  
    110.        
    111.      fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;  
    112.     }  
    113.    }  
    114.    fullTemplate += e.template.mid;  
    115.   
    116.    if ($.isArray(table)) {  
    117.     for (i in table) {  
    118.      fullTemplate += e.template.table.head + «{table» + i + «}» + e.template.table.tail;  
    119.     }  
    120.    }  
    121.    fullTemplate += e.template.foot;  
    122.    for (i in table) {  
    123.     e.ctx[«table» + i] = table[i];  
    124.    }  
    125.    delete e.ctx.table;  
    126.    var isIE =  false || !!document.documentMode;   
    127.      
    128.    if (isIE) {  
    129.     if (typeof Blob !== «undefined») {  
    130.        
    131.      fullTemplate = e.format(fullTemplate, e.ctx);   
    132.      fullTemplate = [fullTemplate];  
    133.        
    134.      var blob1 = new Blob(fullTemplate, {  
    135.       type: «text/html»  
    136.      });  
    137.      window.navigator.msSaveBlob(blob1, getFileName(e.settings));  
    138.     } else {  
    139.        
    140.        
    141.      txtArea1.document.open(«text/html»«replace»);  
    142.      txtArea1.document.write(e.format(fullTemplate, e.ctx));  
    143.      txtArea1.document.close();  
    144.      txtArea1.focus();  
    145.      sa = txtArea1.document.execCommand(«SaveAs»true, getFileName(e.settings));  
    146.     }  
    147.    } else {  
    148.     var blob = new Blob([e.format(fullTemplate, e.ctx)], {  
    149.      type: «application/vnd.ms-excel»  
    150.     });  
    151.     window.URL = window.URL || window.webkitURL;  
    152.     link = window.URL.createObjectURL(blob);  
    153.     a = document.createElement(«a»);  
    154.     a.download = getFileName(e.settings);  
    155.     a.href = link;  
    156.     document.body.appendChild(a);  
    157.     a.click();  
    158.     document.body.removeChild(a);  
    159.    }  
    160.    return true;  
    161.   }  
    162.  };  
    163.  function getFileName(settings) {  
    164.   return (settings.filename ? settings.filename : «table2excel»);  
    165.  }  
    166.    
    167.  function exclude_img(string) {  
    168.   var _patt = /(s+alts*=s*«([^»]*)»|s+alts*=s*‘([^’]*)’)/i;  
    169.   return string.replace(/<img[^>]*>/gi, function myFunction(x) {  
    170.    var res = _patt.exec(x);  
    171.    if (res !== null && res.length >= 2) {  
    172.     return res[2];  
    173.    } else {  
    174.     return «»;  
    175.    }  
    176.   });  
    177.  }  
    178.    
    179.  function exclude_links(string) {  
    180.   return string.replace(/<a[^>]*>|</a>/gi, «»);  
    181.  }  
    182.    
    183.  function exclude_inputs(string) {  
    184.   var _patt = /(s+values*=s*«([^»]*)»|s+values*=s*‘([^’]*)’)/i;  
    185.   return string.replace(/<input[^>]*>|</input>/gi, function myFunction(x) {  
    186.    var res = _patt.exec(x);  
    187.    if (res !== null && res.length >= 2) {  
    188.     return res[2];  
    189.    } else {  
    190.     return «»;  
    191.    }  
    192.   });  
    193.  }  
    194.  $.fn[pluginName] = function(options) {  
    195.   var e = this;  
    196.   e.each(function() {  
    197.    if (!$.data(e, «plugin_» + pluginName)) {  
    198.     $.data(e, «plugin_» + pluginName, new Plugin(this, options));  
    199.    }  
    200.   });  
    201.     
    202.   return e;  
    203.  };  
    204. })(jQuery, window, document);  

    HTML Markup

    Now, create another text document within the root directory of your project and save it with the name of «Example.html».

    After this, write the following code within your created Example.html file and save it. 

    1. <html  
    2.     xmlns=«http://www.w3.org/1999/xhtml»>  
    3.     <head>  
    4.         <title></title>  
    5.         <style type=«text/css»>    
    6.         body    
    7.         {    
    8.             font-family: Arial;    
    9.             font-size: 10pt;    
    10.         }    
    11.         table    
    12.         {    
    13.             border: 1px solid #ccc;    
    14.             border-collapse: collapse;    
    15.         }    
    16.         table th    
    17.         {    
    18.             background-color: #ff7f00;    
    19.             color: #fff;    
    20.             font-weight: bold;    
    21.         }    
    22.         table th, table td    
    23.         {    
    24.             padding: 5px;    
    25.             border: 1px solid #ccc;    
    26.         }    
    27.     </style>  
    28.     </head>  
    29.     <body>  
    30.         <table id=«tblEmployee» cellspacing=«0» cellpadding=«0»>  
    31.             <tr>  
    32.                 <th>Employee Id</th>  
    33.                 <th>Employee Name</th>  
    34.                 <th>Department</th>  
    35.             </tr>  
    36.             <tr>  
    37.                 <td>1</td>  
    38.                 <td>Nikunj Satasiya</td>  
    39.                 <td>Asp.Net</td>  
    40.             </tr>  
    41.             <tr>  
    42.                 <td>2</td>  
    43.                 <td>Hiren Dobariya</td>  
    44.                 <td>PHP</td>  
    45.             </tr>  
    46.             <tr>  
    47.                 <td>3</td>  
    48.                 <td>Vivek Ghadiya</td>  
    49.                 <td>Android</td>  
    50.             </tr>  
    51.             <tr>  
    52.                 <td>4</td>  
    53.                 <td>Pratik Pansuriya</td>  
    54.                 <td>SEO</td>  
    55.             </tr>  
    56.         </table>  
    57.         <br />  
    58.         <input type=«button» id=«btnExporttoExcel» value=«Export To Excel» />  
    59.         <script type=«text/javascript» src=«https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js»></script>  
    60.         <script src=«table2excel.js» type=«text/javascript»></script>  
    61.         <script type=«text/javascript»>    
    62.         $(function () {    
    63.             $(«#btnExporttoExcel»).click(function () {    
    64.                 $(«#tblEmployee»).table2excel({    
    65.                     filename: «Your_File_Name.xls»    
    66.                 });    
    67.             });    
    68.         });    
    69.     </script>  
    70.     </body>  
    71. </html>    

    NOTE

    At the end of table tag </table>, you need to add the following script.

    1. $(«#yourHtmTable»).table2excel({  
    2.  exclude: «.excludeThisClass»,  
    3.  name: «Worksheet Name»,  
    4.  filename: «SomeFile»  
    5. });   

    Screenshots/Output

    Output 

    The screen after exporting HTML table to Excel sheet.

    Output 

    Summary

    When the Export to Excel button is clicked, the jQuery table2excel plugin is applied to the created HTML table. The jQuery table2excel plugin accepts the file name as a parameter which sets the name of the Excel file.


    • Posted: 15 Sep 2017
    • Modified: 29 Oct 2022
    • Author:
      • Comments: 0
      • Views: 51285
    • Excel
    • jQuery
    • jQuery Plugins
    • HTML
    • Table

    Here Mudassar Khan has explained with an example, how to convert (export) HTML Table to Excel file using jQuery.

    This article will explain how to convert (export) HTML Table to Excel file with the help of the jQuery table2excel plugin.


    • Download Code


    • Demo

    Download FREE API for Word, Excel and PDF in ASP.Net

    In this article I will explain with an example, how to convert (export) HTML Table to Excel file using jQuery.

    This article will explain how to convert (export) HTML Table to Excel file with the help of the jQuery table2excel plugin.

    HTML Markup

    The following HTML Markup consists of an HTML Table and a Button.

    <table id=»tblCustomers» cellspacing=»0″ cellpadding=»0″>

        <tr>

            <th>Customer Id</th>

            <th>Name</th>

            <th>Country</th>

        </tr>

        <tr>

            <td>1</td>

            <td>John Hammond</td>

            <td>United States</td>

        </tr>

        <tr>

            <td>2</td>

            <td>Mudassar Khan</td>

            <td>India</td>

        </tr>

        <tr>

            <td>3</td>

            <td>Suzanne Mathews</td>

            <td>France</td>

        </tr>

        <tr>

            <td>4</td>

            <td>Robert Schidner</td>

            <td>Russia</td>

        </tr>

    </table>

    <br />

    <input type=»button» id=»btnExport» value=»Export» />

    <script type=»text/javascript» src=»https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js»></script>

    <script src=»table2excel.js» type=»text/javascript»></script>

    <script type=»text/javascript»>

        $(function () {

            $(«#btnExport»).click(function () {

                $(«#tblCustomers»).table2excel({

                    filename: «Table.xls»

                });

            });

        });

    </script>

    Explanation:

    Note: You will get a Warning message from Microsoft Excel application when you try to open the generated Excel file. This Warning is shown because the generated file is not a valid Excel format as the plugin simply exports the HTML content to an Excel file.

    Screenshots

    The HTML Table

    Convert (Export) HTML Table to Excel file using jQuery

    Excel file being downloaded when Export Button is clicked

    Convert (Export) HTML Table to Excel file using jQuery

    The generated Excel file

    Convert (Export) HTML Table to Excel file using jQuery

    Browser Compatibility

    The above code has been tested in the following browsers.

    Internet Explorer  FireFox  Chrome  Safari  Opera

    * All browser logos displayed above are property of their respective owners.

    Demo

    Downloads

    Download Free Word/PDF/Excel API

    YouTube Video


    Comments


    Comments not available for this article.

    jQuery Datatables provides a convenient way to export data to Excel format. This jQuery Datatables tutorial help to create export datatable to excel format using HTML5 and buttons table tools. The excel file format are using .xls and .xlsx extension.

    Excel is one of the most popular file formats used to store tabular data in spreadsheets. We can use Excel format data to import and export data and store into an excel file.

    You can use this functionality only latest browsers and above IE8. The Buttons extension for DataTables provides three plug-ins that provide overlapping functionality for data export.

    • HTML5 export buttons – makes use of HTML5 APIs to create files client-side
    • Flash export buttons – uses Adobe Flash for legacy browsers
    • Print button

    You can also check other tutorials of export table data,

    • Exporting a DataTable into PDF File
    • Exporting a DataTable to CSV
    • DataTables Export to Excel using HTML5
    • Popular JavaScript and jQuery PDF Viewer Plugins

    I am extending excelHtml5 so that you can use export to excel only on the latest browser, not on a legacy browser. I am explaining step by step jQuery datatable export to excel tutorial.

    I am extending the previous tutorial that’s why I will change the extension format and label from the previous Export jQuery datatable to pdf tutorial.

    We have learned Export Datatable to CSV and Export Datatable to PDF in earlier datatables tutorials, Now I am extending this datatables tutorial and adding export datatable to Excel file.

    Exporting jQuery Datatables data to Excel File

    Step 1: We need to include all datatables library files in the head section of index.html file. Let’s include the jQuery library, jQuery Datatables library, and the Buttons extension library.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css">
    <script type="text/javascript" src="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.js"></script>

    Step 2: Created HTML layout for jQuery datatables listing in index.html file.

    <table id="listing" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>User ID</th>
    
                <th>Title</th>
    
                <th>Body</th>
            </tr>
        </thead>
    </table>

    Step 3: Fetched data from restful web service and processed data as required for jQuery datatables.

    var arrayReturn = [];
                $.ajax({
                    url: "http://jsonplaceholder.typicode.com/posts",
                    async: true,
                    dataType: 'json',
                    success: function (data) {
    					for (var i = 0, len = data.length; i &lt; len; i++) {
    						var desc = data[i].body;
    						var title = data[i].title;
    						var id = (data[i].id).toString();
    						arrayReturn.push([id, '<a href="http://google.com" target="_blank">'+title.substring(0, 20)+'</a>', desc.substring(0, 120)]);
    					}
    				inittable(arrayReturn);
                    }
                });

    Step 4: Now I will pass formatted data to the jQuery datatables "aaData" property.

    function inittable(data) {	
    		$('#listing').DataTable({
    			"aaData": data,
    			"dom": 'lBfrtip',
    			buttons: [
                {
                    extend: 'excelHtml5',
                    text: 'Export to Excel',
    				title: 'js-tutorials.com : Export to datatable data to Excel',
    				 download: 'open',
    				 orientation:'landscape',
    				  exportOptions: {
    				  columns: ':visible'
    				}
                }]
    		} );
    	}

    in the above code, I am using excelHtml5 plugin to overlap excel export functionality using html5 api. I have added the title and button text as well.

    You can download the source code and Demo from the below link.

    1. Introduction

    TableHTMLExport jQuery plugin that exports an HTML table to JSON, CSV, TXT, or PDF and force the browser to download the generated file. The plugin without additionally server requests can export HTML table and download its content. Using this plugin is a simple way to reduce the costs of running applications because for every request is resource-hungry.

    Export html table to csv pdf text text file

    2. Plugin Overview

    Demo

    3. How to install and use TableHTMLExport jQuery plugin

    Follow below steps in order to install TableHTMLExport jQuery plugin.

    1. first of all load jQuery JavaScript library:

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    

    2. second step is to include TableHTMLExport plugin:

    <!-- Table HTML Export Js -->
    <script src="js/tableHTMLExport.js"></script>
    

    3. next, create a sample HTML table with export button:

      <table id="myTable">
      <thead>
        <tr>
          <th>Customer</th>
          <th>Contact</th>
          <th>Country</th>
      </tr>    
      </thead>
      <tbody>
        <tr>
          <td>FrontBackend</td>
          <td>Martin Wojtus</td>
          <td>France</td>
        </tr>
        <tr>
          <td>Ernst Handel</td>
          <td>Roland Mendel</td>
          <td>Austria</td>
        </tr>
        <tr>
          <td>Island Trading</td>
          <td>Helen Bennett</td>
          <td>UK</td>
        </tr>
        <tr>
          <td>Magazzini Alimentari Riuniti</td>
          <td>Giovanni Rovelli</td>
          <td>Italy</td>
        </tr>
      </tbody>  
    </table>
    
    <button class="export-btn"><i class="fa fa-file-excel-o"></i> Export to Excel</button>
    

    4. final step is to initialize the tableHTMLExport plugin:

    $(document).ready(function(){
       $(".export-btn").click(function(){  
         $("#tableCustomers").tableHTMLExport({
          type:'csv',
          filename:'frontbackend-html-table-to-excel.csv',
        });
      });
    });
    

    tableHTMLExport plugin is used ad hoc, at the moment when we need to export the table and download file.

    4. Conclusion

    In this article, we showcased tableHTMLExport jQuery plugin that allows you to export any HTML table to CSV/PDF/TXT/JSON file. The plugin is a great way to download table reports without involving the backend side of the application. tableHTMLExport plugin is simple to use, just select a table using jQuery selectors, choose the result file type (you can choose between CSV, PDF, text, and JSON) and a filename and run the plugin.

    Like this post? Please share to your friends:
  • Export table from php to excel
  • Expression with the word horses
  • Export sql queries to excel
  • Expression with the word heart
  • Export sql into excel