Ultimate HTML Table Export Plugin With jQuery - tableExport.js

Ultimate HTML Table Export Plugin With jQuery - tableExport.js
File Size: 8.51 KB
Views Total: 271
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Do you need to export an HTML table to JSON, XML, CSV, TSV, TXT, SQL, DOC, XLS, XLSX, PNG, or PDF format? If so, then this jQuery plugin is for you.

tableExport.js is a jQuery plugin that makes it easy to export tables in any of these formats with just a few lines of code. Open source and free to use. Plus, it's customizable so that you can configure it to match your needs. So check it out and start exporting your tables today!

How to use it:

1. Load the necessary JavaScript libraries before importing the tableExport.js plugin.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/cdn/FileSaver.min.js"></script>
<script src="/path/to/cdn/xlsx.core.min.js"></script>
<!-- For IE11 support include polyfills.umd.js before you include jspdf.umd.min.js and html2canvas.min.js -->
<script src="/path/to/cdn/jsPDF/polyfills.umd.js"></script>
<script src="/path/to/cdn/jsPDF/jspdf.umd.min.js"></script>
<script src="/path/to/cdn/html2canvas/html2canvas.min.js"></script>

2. Download and load the minified version of the tableExport.js plugin.

<script src="/path/to/tableExport.min.js"></script>

3. Export data from tables into different formats.

<table id="myTable">
  ...
</table>
// To CSV
$('#myTable').tableExport();

// To TSV
$('#myTable').tableExport({
  type: 'tsv'
});

// To Text
$('#myTable').tableExport({
  type: 'txt'
});

// To SQL
$('#myTable').tableExport({
  type: 'sql'
});

// To JSON
$('#myTable').tableExport({
  type: 'json'
});

// To XML
$('#myTable').tableExport({
  type: 'xml'
});

// To XLS
$('#myTable').tableExport({
  type: 'excel'
});

// To XLSX
$('#myTable').tableExport({
  type: 'excel',
  mso: {
    fileFormat:'xmlss',
    worksheetName: ['Table 1','Table 2', 'Table 3']
  }
});

// To DOC
$('#myTable').tableExport({
  type: 'doc'
});

// To PNG
$('#myTable').tableExport({
  type: 'png'
});

// To PDF 
// using jsPDF
$('#myTable').tableExport({
  type: 'pdf',
  jspdf: {
    // jsPDF options
  }
});

// To PDF 
// using jsPDF and jsPDF Autotable 
$('#myTable').tableExport({
  type: 'pdf',
  jspdf: {
    // jsPDF options
    autotable: {
      // autotable options
    }
  }
});

// To PDF 
// with callbacks
$('#myTable').tableExport({
  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
      }
    }
  }
});

// To PDF 
// using pdfmake
$('#myTable').tableExport({
  type: 'pdf',
  pdfmake:{
    enabled:true,
    docDefinition:{
      pageOrientation:'landscape'
    },
    // more pdfmake options
  }
});

4. All default plugin options.

$('#myTable').tableExport({
  csvEnclosure: '"',
  csvSeparator: ',',
  csvUseBOM: true,
  date: {
    // Date format used in html source. 
    // Supported placeholders: dd, mm, yy, yyyy and a arbitrary single separator character
    html: 'dd/mm/yyyy'              
  },                                
  // true = speed up export of large tables with hidden cells (hidden cells will be exported !)
  exportHiddenCells: false,         
  fileName: 'tableExport',          
  htmlContent: false,       
  // Export the 'content' or the 'href' link of <a> tags unless onCellHtmlHyperlink is not defined        
  htmlHyperlink: 'content',         
  ignoreColumn: [],                 
  ignoreRow: [],      
  // One of 'head', 'data', 'all'              
  jsonScope: 'all',         
  // jsPDF / jsPDF-AutoTable related options        
  jspdf: {                          
    orientation: 'p',               
    unit: 'pt',
    // One of jsPDF page formats or 'bestfit' for automatic paper format selection        
    format: 'a4',                   
    margins: {left: 20, right: 10, top: 10, bottom: 10},
    onDocCreated: null,
    autotable: {
      styles: {
        cellPadding: 2,
        rowHeight: 12,
        fontSize: 8,
        // Color value or 'inherit' to use css background-color from html table
        fillColor: 255,             
        // Color value or 'inherit' to use css color from html table
        textColor: 50,       
        // 'normal', 'bold', 'italic', 'bolditalic' or 'inherit' to use css font-weight and font-style from html table       
        fontStyle: 'normal',        
        // 'visible', 'hidden', 'ellipsize' or 'linebreak'
        overflow: 'ellipsize',
        // 'left', 'center', 'right' or 'inherit' to use css horizontal cell alignment from html table      
        halign: 'inherit',    
        // 'top', 'middle', or 'bottom'      
        valign: 'middle'            
      },                          
      headerStyles: {             
        fillColor: [52, 73, 94],  
        textColor: 255,           
        fontStyle: 'bold',    
        // 'left', 'center', 'right' or 'inherit' to use css horizontal header cell alignment from html table    
        halign: 'inherit',       
        // 'top', 'middle', or 'bottom'   
        valign: 'middle'            
      },                          
      alternateRowStyles: {       
        fillColor: 245            
      },                          
      tableExport: {   
        // jsPDF doc object. If set, an already created doc object will be used to export to           
        doc: null,                  
        onAfterAutotable: null,
        onBeforeAutotable: null,
        onAutotableText: null,
        onTable: null,
        outputImages: true
      }
    }
  },
  // MS Excel and MS Word related options
  mso: { 
    // 'xlshtml' = Excel 2000 html format
    // 'xmlss' = XML Spreadsheet 2003 file format (XMLSS)
    // 'xlsx' = Excel 2007 Office Open XML format          
    fileFormat: 'xlshtml',
    // Excel 2000 html format only. See readme.md for more information about msonumberformat
    onMsoNumberFormat: null,        
    // Page format used for page orientation
    pageFormat: 'a4',               
    // portrait, landscape (xlshtml format only)
    pageOrientation: 'portrait',  
    // true = Set worksheet option 'DisplayRightToLeft'  
    rtl: false,     
    // E.g. ['border-bottom', 'border-top', 'border-left', 'border-right']                
    styles: [],                     
    worksheetName: '',
    // Specific Excel 2007 XML format settings:
    xlsx: {   
      // XLSX format (id) used to format excel cells. See readme.md: data-tableexport-xlsxformatid                      
      formatId: {    
        // formatId or format string (e.g. 'm/d/yy') or function(cell, row, col) {return formatId}               
        date: 14,       
        // formatId or format string (e.g. '\"T\"\ #0.00') or function(cell, row, col) {return formatId}            
        numbers: 2                  
      },
      // function($cell, row, col, href, content, hyperlink): Return what to export for hyperlinks
      onHyperlink: null             
    }
  },
  numbers: {
    html: {
      // Decimal mark in html source
      decimalMark: '.',             
      // Thousands separator in html source
      thousandsSeparator: ','       
    },
    // Set 'output: false' to keep number format of html source in resulting output
    output: {                      
      // Decimal mark in resulting output 
      decimalMark: '.',      
      // Thousands separator in resulting output       
      thousandsSeparator: ','       
    }
  },
  // 'file', 'string', 'base64' or 'window' (experimental)
  outputMode: 'file',               
  pdfmake: {
    // true: Use pdfmake as pdf producer instead of jspdf and jspdf-autotable
    enabled: false,                 
    docDefinition: {
      // 4A0,2A0,A{0-10},B{0-10},C{0-10},RA{0-4},SRA{0-4},EXECUTIVE,FOLIO,LEGAL,LETTER,TABLOID
      pageSize: 'A4',               
      // 'portrait' or 'landscape'
      pageOrientation: 'portrait',  
      styles: {
        header: {
          background: '#34495E',
          color: '#FFFFFF',
          bold: true,
          alignment: 'center',
          fillColor: '#34495E'
        },
        alternateRow: {
          fillColor: '#f5f5f5'
        }
      },
      defaultStyle: {
        color: '#000000',
        fontSize: 8,
        // Default font is 'Roboto' which needs vfs_fonts.js to be included
        // To export arabic characters include mirza_fonts.js _instead_ of vfs_fonts.js
        // For a chinese font include either gbsn00lp_fonts.js or ZCOOLXiaoWei_fonts.js _instead_ of vfs_fonts.js 
        font: 'Roboto'              
      }                             
    },                              
    fonts: {}
  },
  preserve: {
    // preserve leading white spaces
    leadingWS: false,               
    // preserve trailing white spaces
    trailingWS: false               
  },
  // Prepend a single quote to cell strings that start with =,+,- or @ to prevent formula injection
  preventInjection: true,           
  sql: {
    // If table name or column names contain any characters except letters, numbers, and
    // underscores, usually the name must be delimited by enclosing it in back quotes (`)
    tableEnclosure: '`',            
    columnEnclosure: '`'            
  },
  tbodySelector: 'tr',
  // Set empty ('') to prevent export of tfoot rows
  tfootSelector: 'tr',              
  theadSelector: 'tr',
  tableName: 'Table',
  // Export format: 'csv', 'tsv', 'txt', 'sql', 'json', 'xml', 'excel', 'doc', 'png' or 'pdf'
  type: 'csv'                       
});

5. Callback functions.

$('#myTable').tableExport({

  // function(data, fileName)
  onAfterSaveToFile: null,          

  // function(data, fileName, type, charset, encoding)
  onBeforeSaveToFile: null,         

  // function($cell, row, col, href, cellText, cellType)
  onCellData: null,                 

  // function($cell, row, col, htmlContent)
  onCellHtmlData: null,             

  // function($cell, row, col, href, cellText)
  onCellHtmlHyperlink: null,        

  // function($tr, row): Return true to prevent export of the row
  onIgnoreRow: null,                

  // called when export starts
  onTableExportBegin: null,        

  // called when export ends       
  onTableExportEnd: null,   

});

6. Available HTML data attributes.

<!-- An empty data value preserves format of cell content -->
<table id="myTable">
  ...
  <td data-tableexport-cellformat="">
    ...
  </td>
  ...
</table>

<!-- Overwrites the colspan attribute of the table cell during export -->
<table id="myTable">
  ...
  <td colspan="2" data-tableexport-colspan="3">
    ...
  </td>
  ...
</table>

<!-- Overwrites the rowspan attribute of the table cell during export -->
<table id="myTable">
  ...
  <td rowspan="2" data-tableexport-rowspan="3">
    ...
  </td>
  ...
</table>

<!-- Customize titles -->
<table id="myTable">
  ...
  <th data-tableexport-value="TH title">
    ...
  </th>
  <td data-tableexport-value="CELL title">
    ...
  </td>
  ...
</table>

<!-- Exclude & Include tables & cells -->
<table id="myTable" data-tableexport-display="always">
  ...
  <td data-tableexport-display="none">
    ...
  </td>
  ...
</table>

<!-- 
  "\@"                        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
  "\0022£\0022\#\,\#\#0\.00"  £12.76
  "\#\,\#\#0\.00_ \;\[Red\]\-\#\,\#\#0\.00\ "  2 decimals, negative red numbers
 -->
<table id="myTable">
  ...
  <td data-tableexport-msonumberformat="0\.000">
    ...
  </td>
  ...
</table>

<!-- 
  "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秒
-->
<table id="myTable">
  ...
  <td data-tableexport-xlsxformatid="14">
    ...
  </td>
  ...
</table>

This awesome jQuery plugin is developed by hhurz. For more Advanced Usages, please check the demo page or visit the official website.