Skip to content

Commit

Permalink
Merge pull request #88 from jmaister/filter-rows-columns
Browse files Browse the repository at this point in the history
Filter rows and columns
  • Loading branch information
jmaister authored Feb 16, 2019
2 parents aacd543 + 50c70fd commit 15fbb9b
Show file tree
Hide file tree
Showing 8 changed files with 3,597 additions and 1,261 deletions.
88 changes: 48 additions & 40 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,18 @@ Check my blog page for testing:

# TODO:

* Define the final API for ExcellentExport.convert(...)
* Remove rows or columns from a table.
* Filter and process cell values.
* Output as a Blob.
* Set fonts to the sheet.
* Insert images ?

# Revision history:

### 3.3.0

* Remove columns by index
* Filter rows by value
* Updated build to Webpack 4.x.x

### 3.2.1

* Update npm dependencies to fix vulnerabilities
Expand All @@ -36,31 +39,31 @@ Check my blog page for testing:

* Fix old API for base64 and escaping problem.

### 3.0.0 (22/10/2017)
### 3.0.0

* XLSX support. This bumps the build size to 640 KB.
* New API: ExcellentExport.convert(...)
* Autogenerate download filename.
* Data input from arrays or HTML Tables.
* Multiple sheets for XLS or XLSX formats.

### 2.1.0 (24/09/2017)
### 2.1.0

* Add Webpack build.
* Create UMD JavaScript module. Library can be loaded as a module (import, RequireJS, AMD, etc...) or standalone as window.ExcelentExport.

### 2.0.3 (21/01/2017)
### 2.0.3

* Fix export as a module.
* Changed minifier to UglifyJS.

### 2.0.2 (10/01/2017)
### 2.0.2

* Fix CSV Chinese characters and other special characters display error in Windows Excel.
* Fix URL.createObjectURL(...) on Firefox.


### 2.0.0 (03/10/2016)
### 2.0.0

* Now it can export to big files +2MB.
* Minimum IE 11.
Expand Down Expand Up @@ -99,62 +102,40 @@ Firefox, Chrome, Internet Explorer 11+.

# Install

## Bower

bower install excellentexport


## npm

npm install excellentexport

## Composer
npm install excellentexport --save

Get [Composer](http://getcomposer.org):
## yarn

$ curl -s http://getcomposer.org/installer | php
$ php composer.phar install
yarn add excellentexport

Create a composer.json file for your project:

```JSON
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/jmaister/excellentexport"
}
],
"require": {
"jmaister/excellentexport": "~1.4.0"
}
}
```
## Bower

Run `composer install`.
bower install excellentexport

# Load


Include script in your HTML:


<script type="text/javascript" src="/components/excellentexport/dist/excellentexport.js"></script>
<script type="text/javascript" src="dist/excellentexport.js"></script>


Require.js

<script src="http://requirejs.org/docs/release/2.3.2/minified/require.js"></script>
<script src="http://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
<script>
require(['dist/excellentexport'], function(ee) {
window.ExcellentExport = ee;
});
</script>

Import
ES6 import

import ExcellentExport from 'excellentexport';


# Usage

<table id="datatable">
Expand All @@ -171,6 +152,29 @@ Import
<!-- new API, xlsx -->
<a download="somedata.xlsx" href="#" onclick="return ExcellentExport.convert({ anchor: this, filename: 'data_123.array', format: 'xlsx'},[{name: 'Sheet Name Here 1', from: {table: 'datatable'}}]);">Export to CSV</a>

# API

ExcellentExport.convert(options, sheets);

Options:
{
anchor: String/Element,
format: 'xlsx'/'xls'/'csv',
filename: String
}

Sheet element configuration:
{
name: 'Sheet 1', // Sheet name
from: {
table: String/Element, // Table ID or table element
array: [...], // Array with data
arrayHasHeader: true, // Array first row is the header
removeColumns: [...], // Array of column indexes (from 0)
filterRowFn: function(row) {return true} // Return true to keep
},
...
}

# Notes

Expand All @@ -192,10 +196,14 @@ Install dependencies:

npm install

Build dist/excellentexport.js
Build development version dist/excellentexport.js

npm run build

Build publish version of dist/excellentexport.js

npm run prod

Publish

npm publish
23 changes: 0 additions & 23 deletions composer.json

This file was deleted.

5 changes: 3 additions & 2 deletions dist/excellentexport.js

Large diffs are not rendered by default.

65 changes: 50 additions & 15 deletions excellentexport.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* ExcellentExport 3.0.0
* ExcellentExport 3.2.1
* A client side Javascript export to Excel.
*
* @author: Jordi Burgos ([email protected])
Expand Down Expand Up @@ -48,22 +48,36 @@ const ExcellentExport = function() {
const template = {excel: '<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"><head><meta name=ProgId content=Excel.Sheet> <meta name=Generator content="Microsoft Excel 11"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'};
let csvDelimiter = ",";
let csvNewLine = "\r\n";
/**
* Convert a string to Base64.
*
* @param {string} s
*/
const base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)));
};

const format = function(s, c) {
return s.replace(new RegExp("{(\\w+)}", "g"), function(m, p) {
return c[p];
});
};


/**
* Get element by ID.
* @param {*} element
*/
const get = function(element) {
if (!element.nodeType) {
return document.getElementById(element);
}
return element;
};

/**
* Encode a value for CSV.
* @param {*} value
*/
const fixCSVField = function(value) {
let fixedValue = value;
const addQuotes = (value.indexOf(csvDelimiter) !== -1) || (value.indexOf('\r') !== -1) || (value.indexOf('\n') !== -1);
Expand Down Expand Up @@ -137,13 +151,16 @@ const ExcellentExport = function() {
}
};

const removeColumn = function(arr2d, colIndex) {
for (var i = 0; i < arr2d.length; i++) {
var row = arr2d[i];
row.splice(colIndex, 1);
}
};

/*
ExcellentExport.convert(options, sheets);
ExcellentExport.convert({...}, [
{...}, {...},
]);
Options:
{
anchor: String/Element,
Expand All @@ -158,13 +175,11 @@ const ExcellentExport = function() {
table: String/Element, // Table ID or table element
array: [...], // Array with data
arrayHasHeader: true, // Array first row is the header
filter: function(row, col, data) {}
removeColumns: [...], // Array of column indexes (from 0)
filterRowFn: function(row) {return true}
},
...
}
https://github.com/SheetJS/js-xlsx#utility-functions
*/
const convert = function(options, sheets) {
let workbook = {
Expand All @@ -179,22 +194,42 @@ const ExcellentExport = function() {
throw new Error("'csv' format only supports one sheet");
}

sheets.forEach((sheetConf) => {
sheets.forEach((sheetConf, index) => {
const name = sheetConf.name;
if (!name) {
throw new Error('Sheets must have "name".');
throw new Error('Sheet ' + index + ' must have the property "name".');
}

// Select data source
let worksheet = null;
let dataArray;
if (sheetConf.from && sheetConf.from.table) {
const dataArray = tableToArray(get(sheetConf.from.table));
worksheet = XLSX.utils.aoa_to_sheet(dataArray, {sheet: name});
dataArray = tableToArray(get(sheetConf.from.table));
} else if(sheetConf.from && sheetConf.from.array) {
worksheet = XLSX.utils.aoa_to_sheet(sheetConf.from.array, {sheet: name});
dataArray = sheetConf.from.array
} else {
throw new Error('No data for sheet: [' + name + ']');
}

// Filter data
console.log("conf", sheetConf);
if (sheetConf.filterRowFn) {
if (sheetConf.filterRowFn instanceof Function) {
dataArray = dataArray.filter(sheetConf.filterRowFn);
} else {
throw new Error('Parameter "filterRowFn" must be a function.');
}
}
if (sheetConf.removeColumns) {
const toRemove = sheetConf.removeColumns.sort().reverse();
toRemove.forEach(index => {
removeColumn(dataArray, index);
});
}

// Create sheet
workbook.SheetNames.push(name);
worksheet = XLSX.utils.aoa_to_sheet(dataArray, {sheet: name});
workbook.Sheets[name] = worksheet;
});

Expand Down
Loading

0 comments on commit 15fbb9b

Please sign in to comment.