• This repository has been archived on 25/Jul/2021
  • Stars
    star
    879
  • Rank 51,943 (Top 2 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The simple, easy-to-implement library to export HTML tables to xlsx, xls, csv, and txt files.

TableExport

NPM release Build Status Downloads License

Docs

Getting Started

Install manually using <script> tags

To use this library, include the FileSaver.js library, and TableExport library before the closing <body> tag of your HTML document:

<script src="FileSaver.js"></script>
...
<script src="tableexport.js"></script>

Install with Bower

$ bower install tableexport.js

Install with npm

$ npm install tableexport

CDN

unpkg

uncompressed compressed
CSS 🔗 🔗
JS 🔗 🔗
Images 🔗xlsx🔗xls🔗csv🔗txt

Dependencies

Required:

Optional:

Add-Ons:

In order to provide Office Open XML SpreadsheetML Format ( .xlsx ) support, you must include the following third-party library in your project before both FileSaver.js and TableExport.

Including xlsx.core.js is NOT necessary if installing with Bower or npm

<script src="xlsx.core.js"></script>
<script src="FileSaver.js"></script>
...
<script src="tableexport.js"></script>

Older Browsers:

To support legacy browsers ( Chrome < 20, Firefox < 13, Opera < 12.10, IE < 10, Safari < 6 ) include the Blob.js polyfill before the FileSaver.js script.

  • Blob.js by eligrey (forked by clarketm)

Including Blob.js is NOT necessary if installing with Bower or npm

<script src="Blob.js"></script>
<script src="FileSaver.js"></script>
...
<script src="tableexport.js"></script>

Usage

JavaScript

To use this library, simple call the TableExport constructor:

new TableExport(document.getElementsByTagName("table"));

// OR simply

TableExport(document.getElementsByTagName("table"));

// OR using jQuery

$("table").tableExport();

Additional properties can be passed-in to customize the look and feel of your tables, buttons, and exported data.

Notice that by default, TableExport will create export buttons for three different filetypes xls, csv, txt. You can choose which buttons to generate by setting the formats property to the filetype(s) of your choice.

/* Defaults */
TableExport(document.getElementsByTagName("table"), {
  headers: true,                      // (Boolean), display table headers (th or td elements) in the <thead>, (default: true)
  footers: true,                      // (Boolean), display table footers (th or td elements) in the <tfoot>, (default: false)
  formats: ["xlsx", "csv", "txt"],    // (String[]), filetype(s) for the export, (default: ['xlsx', 'csv', 'txt'])
  filename: "id",                     // (id, String), filename for the downloaded file, (default: 'id')
  bootstrap: false,                   // (Boolean), style buttons using bootstrap, (default: true)
  exportButtons: true,                // (Boolean), automatically generate the built-in export buttons for each of the specified formats (default: true)
  position: "bottom",                 // (top, bottom), position of the caption element relative to table, (default: 'bottom')
  ignoreRows: null,                   // (Number, Number[]), row indices to exclude from the exported file(s) (default: null)
  ignoreCols: null,                   // (Number, Number[]), column indices to exclude from the exported file(s) (default: null)
  trimWhitespace: true,               // (Boolean), remove all leading/trailing newlines, spaces, and tabs from cell text in the exported file(s) (default: false)
  RTL: false,                         // (Boolean), set direction of the worksheet to right-to-left (default: false)
  sheetname: "id"                     // (id, String), sheet name for the exported spreadsheet, (default: 'id')
});

Note: to use the xlsx filetype, you must include js-xlsx; reference the Add-Ons section.

Properties

Methods

TableExport supports additional methods (getExportData, update, reset and remove) to control the TableExport instance after creation.

/* First, call the `TableExport` constructor and save the return instance to a variable */
var table = TableExport(document.getElementById("export-buttons-table"));

getExportData

/* get export data */
var exportData = table.getExportData(); // useful for creating custom export buttons, i.e. when (exportButtons: false)

/*****************
 ** exportData ***
 *****************
{
    "export-buttons-table": {
        xls: {
            data: "...",
            fileExtension: ".xls",
            filename: "export-buttons-table",
            mimeType: "application/vnd.ms-excel"
        },
        ...
    }
};
*/

export2file

/* convert export data to a file for download */
var exportData = table.getExportData(); 
var xlsxData = exportData.table.xlsx; // Replace with the kind of file you want from the exportData
table.export2file(xlsxData.data, xlsxData.mimeType, xlsxData.filename, xlsxData.fileExtension, xlsxData.merges, xlsxData.RTL, xlsxData.sheetname)

getFileSize

var tableId = "export-buttons-table";
var XLS = table.CONSTANTS.FORMAT.XLS;

/* get export data (see `getExportData` above) */
var exportDataXLS = table.getExportData()[tableId][XLS];

/* get file size (bytes) */
var bytesXLS = table.getFileSize(exportDataXLS.data, exportDataXLS.fileExtension);

/**********************************
 ** bytesXLS (file size in bytes)
 **********************************
352
*/

update

/* update */
table.update({
  filename: "newFile" // pass in a new set of properties
});

reset

/* reset */
table.reset(); // useful for a dynamically altered table

remove

/* remove */
table.remove(); // removes caption and buttons

Settings

Below are some of the popular configurable settings to customize the functionality of the library.

ignoreCSS

/**
 * CSS selector or selector[] to exclude/remove cells (<td> or <th>) from the exported file(s).
 * @type {selector|selector[]}
 * @memberof TableExport.prototype
 */

// selector
TableExport.prototype.ignoreCSS = ".tableexport-ignore";

// selector[]
TableExport.prototype.ignoreCSS = [".tableexport-ignore", ".other-ignore-class"];

// OR using jQuery

// selector
$.fn.tableExport.ignoreCSS = ".tableexport-ignore";

// selector[]
$.fn.tableExport.ignoreCSS = [".tableexport-ignore", ".other-ignore-class"];

emptyCSS

/**
 * CSS selector or selector[] to replace cells (<td> or <th>) with an empty string in the exported file(s).
 * @type {selector|selector[]}
 * @memberof TableExport.prototype
 */

// selector
TableExport.prototype.emptyCSS = ".tableexport-empty";

// selector[]
TableExport.prototype.emptyCSS = [".tableexport-empty", ".other-empty-class"];

// OR using jQuery

// selector
$.fn.tableExport.emptyCSS = ".tableexport-empty";

// selector[]
$.fn.tableExport.emptyCSS = [".tableexport-empty", ".other-empty-class"];
/* default charset encoding (UTF-8) */
TableExport.prototype.charset = "charset=utf-8";

/* default `filename` property if "id" attribute is unset */
TableExport.prototype.defaultFilename = "myDownload";

/* default class to style buttons when not using Bootstrap or the built-in export buttons, i.e. when (`bootstrap: false` & `exportButtons: true`)  */
TableExport.prototype.defaultButton = "button-default";

/* Bootstrap classes used to style and position the export button, i.e. when (`bootstrap: true` & `exportButtons: true`) */
TableExport.prototype.bootstrapConfig = ["btn", "btn-default", "btn-toolbar"];

/* row delimeter used in all filetypes */
TableExport.prototype.rowDel = "\r\n";
/**
 * Format-specific configuration (default class, content, mimeType, etc.)
 * @memberof TableExport.prototype
 */
formatConfig: {
    /**
     * XLSX (Open XML spreadsheet) file extension configuration
     * @memberof TableExport.prototype
     */
    xlsx: {
        defaultClass: 'xlsx',
        buttonContent: 'Export to xlsx',
        mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        fileExtension: '.xlsx'
    },
    xlsm: {
        defaultClass: 'xlsm',
        buttonContent: 'Export to xlsm',
        mimeType: 'application/vnd.ms-excel.sheet.macroEnabled.main+xml',
        fileExtension: '.xlsm'
    },
    xlsb: {
        defaultClass: 'xlsb',
        buttonContent: 'Export to xlsb',
        mimeType: 'application/vnd.ms-excel.sheet.binary.macroEnabled.main',
        fileExtension: '.xlsb'
    },
    /**
     * XLS (Binary spreadsheet) file extension configuration
     * @memberof TableExport.prototype
     */
    xls: {
        defaultClass: 'xls',
        buttonContent: 'Export to xls',
        separator: '\t',
        mimeType: 'application/vnd.ms-excel',
        fileExtension: '.xls',
        enforceStrictRFC4180: false
    },
    /**
     * CSV (Comma Separated Values) file extension configuration
     * @memberof TableExport.prototype
     */
    csv: {
        defaultClass: 'csv',
        buttonContent: 'Export to csv',
        separator: ',',
        mimeType: 'text/csv',
        fileExtension: '.csv',
        enforceStrictRFC4180: true
    },
    /**
     * TXT (Plain Text) file extension configuration
     * @memberof TableExport.prototype
     */
    txt: {
        defaultClass: 'txt',
        buttonContent: 'Export to txt',
        separator: '  ',
        mimeType: 'text/plain',
        fileExtension: '.txt',
        enforceStrictRFC4180: true
    }
},

//////////////////////////////////////////
// Configuration override example
//////////////////////////////////////////

/* Change the CSV (Comma Separated Values) `mimeType` to "application/csv" */
TableExport.prototype.formatConfig.xlsx.mimeType = "application/csv"

CSS

TableExport packages with customized Bootstrap CSS stylesheets to deliver enhanced table and button styling. These styles can be enabled by initializing with the bootstrap property set to true.

TableExport(document.getElementsByTagName("table"), {
  bootstrap: true
});

When used alongside Bootstrap, there are four custom classes .xlsx, .xls, .csv, .txt providing button styling for each of the exportable filetypes.

Browser Support

Chrome Firefox IE Opera Safari
Android - -
iOS - - -
Mac OSX -
Windows

A full list of browser support can be found in the FileSaver.js README. Some legacy browsers may require an additional third-party dependency: Blob.js

Examples

Customizing Properties

Customizing Settings

Miscellaneous

Skeletons

License

TableExport is licensed under the terms of the Apache-2.0 License

Going Forward

TODOs

  • Update JSDocs and TypScript definition file.
  • Fix bug with CSV and TXT ignoreRows and ignoreCols (rows/cols rendered as empty strings rather than being removed).
  • Reimplement and test the update, reset, and remove TableExport prototype properties without requiring jQuery.
  • Make jQuery as peer dependency and ensure proper TableExport rendering in browser, AMD, and CommonJS environments.
  • Force jQuery to be an optionally loaded module.
  • Use the enhanced SheetJS xls, csv, and txt formats (exposed via enforceStrictRFC4180 prototype property).
  • Allow ignoreCSS and emptyCSS to work with any selector|selector[] instead of solely a single CSS class.
  • Ensure (via testing) full consistency and backwards-compatibility for jQuery.
  • Add Export as PDF support.

Credits

Special thanks the the following contributors:

More Repositories

1

proxy-list

A list of free, public, forward proxy servers. UPDATED DAILY!
2,083
star
2

s3recon

Amazon S3 bucket finder and crawler.
Python
123
star
3

image-map

Responsive, dynamic image maps.
JavaScript
118
star
4

mergedeep

A deep merge function for 🐍.
Python
117
star
5

wait-for-it

Wait for service(s) to be available before executing a command.
Python
63
star
6

zsh-completions

Additional completion definitions for Zsh. UPDATED DAILY!
Shell
50
star
7

json

Drop-in replacement for Golang encoding/json with additional features.
Go
42
star
8

jwt-cli

Command line tool for working with JSON Web Tokens (JWT)
JavaScript
38
star
9

saga-monitor

Simple, elegant, and configurable redux-saga monitor
JavaScript
36
star
10

hugo-elasticsearch

Generate Elasticsearch indexes for Hugo static sites by parsing front matter
JavaScript
27
star
11

java-design-patterns

Catalog of popular object-oriented design patterns in Java
Java
21
star
12

ncalc

Command line utility for quick number base conversions ( ascii / binary / octal / decimal / hexadecimal )
Go
19
star
13

pprintjson

A json pretty printer for Python 🐍
Python
14
star
14

myip

Command line utility for displaying public and private IP addresses
Go
13
star
15

pprintast

An AST pretty printer for Python 🐍
Python
13
star
16

super

Data structures, data types, and algorithms with superpowers! 💪😎
JavaScript
12
star
17

jwt-token-generator

Generate JWT Token using Unix command line tools
Shell
11
star
18

go-bash-wrapper

Run bash scripts with Golang
Go
10
star
19

tableexport_flask_app

TableExport + Flask sample app
Python
9
star
20

highcharts-more

Universal highcharts-more module for the popular JavaScript charting framework Highcharts
JavaScript
8
star
21

hugo-lunr-indexer

Generate Lunr indexes for Hugo static sites by parsing front matter
JavaScript
8
star
22

SortAlgorithms

Sorting algorithm visualization using D3
CSS
8
star
23

React-generators

Generator templates for React using ES6/React best practices
JavaScript
8
star
24

docker-wrapper

Docker command wrapper.
Shell
8
star
25

HackerRank-Python

HackerRank Python Solutions
Python
7
star
26

generator-node-cli-commander

Node command line application generator.
JavaScript
7
star
27

linux-from-scratch

A list of files, scripts, and documentation for Linux From Scratch - Version 8.0
Shell
7
star
28

generator-node-cli

Node command line application generator.
JavaScript
7
star
29

check

Check if a TCP/UDP port is open on a host(s) using UNIX command line tools.
Shell
7
star
30

HackerRank-Java

HackerRank Java Solutions
Java
7
star
31

bitflag

A simple bit flag class for Python 🐍
Python
7
star
32

SearchableList

Extend doubly linked list `list.go` with search methods
Go
7
star
33

csv-2-mongo

Import a CSV to MongoDB
Python
7
star
34

movie-picker

Find something to watch on Netflix when the family is in town!
JavaScript
7
star
35

QueryTag

The simple, easy-to-implement jQuery plugin that allows you to add popular search queries from a Google Custom Search Engine (CSE) to your website as sortable, filterable, and stylable keyword tags.
CSS
7
star
36

i18n-api-node

Internationalization (I18n) API - Node
JavaScript
6
star
37

HackerRank-Bash

HackerRank Bash Solutions
Shell
6
star
38

calculator

React Native calculator
JavaScript
6
star
39

tableexport_angular4_webpack2_app

TableExport + Angular 4 + Webpack 2 sample app
JavaScript
6
star
40

realtime-twitter-feed

Realtime Twitter feed using Angular2, Twitter, Google Maps, Express, and Socket.io
CSS
6
star
41

react-microservice-boilerplate

A scalable React boilerplate with a built-in API layer for modern microservice architectures.
5
star
42

TableExport-docs

TableExport Documentation
CSS
5
star
43

babel-preset-clarketm-react-app

Customized Babel preset for Create React App
JavaScript
5
star
44

systemstat

Command line utility for displaying process and system information
Go
5
star
45

tableexport_webpack-v1_app

TableExport + Webpack1 sample app
JavaScript
5
star
46

tcp

List open TCP connections
Go
5
star
47

public-ip

A simple public IP address API
5
star
48

DeepClone

Light-weight deep clone implementation for JavaScript.
JavaScript
5
star
49

InterviewPracticeProblems

JavaScript
4
star
50

supermap

Map with superpowers!
JavaScript
4
star
51

Jenkins

Jenkins with Docker support
Dockerfile
4
star
52

python-project-skeleton

Python boilerplate and sample project structure.
4
star
53

chatbot

Go
4
star
54

HackerRank-C

HackerRank C/C++ Solutions
C++
4
star
55

superobject

Object with superpowers!
JavaScript
4
star
56

MenuAnimate

Enhance your website with six stylish menu transformicons using SCSS (or LESS) and CSS.
CSS
4
star
57

Rotate

The simple, easy-to-implement animation plugin to rotate icons, images, and elements.
JavaScript
4
star
58

react-lifecycle

Understanding the React Component Lifecycle
JavaScript
4
star
59

tsaleh-vim-tcomment

An easily extensible & universal comment plugin.
Vim Script
4
star
60

blog-api-node

Blog API - Node
JavaScript
4
star
61

HackerRank

HackerRank Solutions
4
star
62

tableexport_requirejs_app

TableExport + RequireJS sample app
HTML
4
star
63

microservice-architecture-node

Scalable microservices system using Loopback and Node.
4
star
64

express-webhook-example

Real-time Express API leveraging Webhooks
JavaScript
4
star
65

express-sse-example

Real-time Express streaming API leveraging Server Sent Events (SSE)
JavaScript
4
star
66

sonos-node

Fork of https://github.com/bencevans/node-sonos optimized for Node v6.10.3 LTS
JavaScript
4
star
67

connect-starhackit-app

JavaScript
3
star
68

connect-dva-app

JavaScript
3
star
69

7DaysOfJavaScript

JavaScript
3
star
70

connect-reactGo-app

JavaScript
3
star
71

connect-react-starter-kit

JavaScript
3
star
72

jzip

JavaScript
3
star
73

HackerRank-JavaScript

HackerRank JavaScript Solutions
JavaScript
3
star
74

ajGingrich.github.io

HTML
3
star
75

i18n-Interpolator

Internationalization (i18n) string interpolator
JavaScript
3
star
76

connect-kyt-app

JavaScript
3
star
77

HungryHokie

Java
3
star
78

connect

JavaScript
3
star
79

connect-reactql-app

JavaScript
3
star
80

UniversalRelayBoilerplate

JavaScript
3
star
81

connect-vulcan-app

JavaScript
3
star
82

create-react-server

JavaScript
3
star
83

aurelia-tutorial

A starter kit for building a standard app with Aurelia.
JavaScript
3
star
84

JavaScript-design-patterns

Catalog of popular object-oriented design patterns using the latest ECMAScript features
3
star
85

pj

Command line tool for working with ProwJobs (PJ)
Go
2
star
86

prow

A Kubernetes based CI/CD system (mirror of kubernetes/test-infra/prow)
Go
2
star
87

Boggle

Boggle
JavaScript
1
star
88

vim

Vim Script
1
star
89

HackerRank-SQL

HackerRank SQL Solutions
1
star
90

gloo-tutorial

Gloo Tutorial
Shell
1
star