jQuery 终极HTML表导出插件 tableExport.js

  • 源码大小:8.77MB
  • 所需积分:1积分
  • 源码编号:19JP-3149
  • 浏览次数:902次
  • 最后更新:2023年05月11日
  • 所属栏目:表格
我要下载
加入收藏
本站默认解压密码:19jp.com 或 19jp_com

简介

您需要将HTML表导出为JSON、XML、CSV、TSV、TXT、SQL、DOC、XLS、XLSX、PNG或PDF格式吗?如果是这样,那么这个jQuery插件就是为你准备的。

tableExport.js是一个jQuery插件,只需几行代码就可以轻松导出这些格式的表。开源且免费使用。此外,它是可定制的,因此您可以根据自己的需求进行配置。所以,看看它,今天就开始导出你的表!

参见:

  • JavaScript中的10个最佳表导出插件

如何使用它:

1.在导入之前加载必要的JavaScript库表格导出.js插件。

  • jQuery
  • 文件保护程序:HTML5 saveAs()文件保护程序
  • SheetJS/js xlsx:以XSLX格式导出
  • jsPDF:客户端JavaScript PDF生成
  • pdfmake:客户端/服务器端PDF打印
  • html2canvas:使用JavaScript的屏幕截图
<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.下载并加载tableExport.js插件的缩小版。

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

3.将表格中的数据导出为不同的格式。

<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.所有默认插件选项。

$('#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 ,
        // This id is used by "data-tableexport-xlsxformatid" to allow you to export a cell in currency format 
        currency: 164,            
      },
      // The format string to be used for the export for the currency format 
      // Euro format: '#,##0.00 €;[Red](#,##0.00) €'
      format: {
        currency: '$#,##0.00;[Red]-$#,##0.00' 
      },
      // 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.回调函数。

$('#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.可用的HTML数据属性。

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

更新日志:

v1.27.0 (2023-03-10)

  • Bugfix。该修复程序现在还允许将用于PDF导出的外部ttf字体与jsPDF集成

v1.26.0 (2022-04-21)

  • XLSX:新选项mso.XLSX.formatid.currency,允许您指定导出货币值的格式

v1.25.0 (2022-04-11)

  • 修复了带有默认onCellHtmlData函数的XSS漏洞

v1.22.0 (2022-03-10)

  • 使用jsPdf导出tp pdf时调用onAfterSaveToFile

预览截图