Skip to content

Commit

Permalink
Add pivot table with limitations
Browse files Browse the repository at this point in the history
```js
worksheet.addPivotTable(configuration);
```

**Note:** Pivot table support is in its early stages with certain limitations, including:

- No support for reading xlsx documents with existing pivot tables (writing is supported).
- Pivot table configurations must consist of 2 rows, 1 column, 1 value, and use the sum metric. The source data can have any number of columns and rows.
- Only one pivot table can be added.
  • Loading branch information
mikez committed Oct 9, 2023
1 parent 3178efd commit f84aaf5
Show file tree
Hide file tree
Showing 17 changed files with 934 additions and 22 deletions.
4 changes: 2 additions & 2 deletions .prettier
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
"bracketSpacing": false,
"printWidth": 100,
"trailingComma": "all",
"bracketSpacing": false,
"arrowParens": "avoid"
"arrowParens": "avoid",
"singleQuote": true,
}
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ npm install exceljs
# New Features!

<ul>
<li>
Merged <a href="https://github.com/exceljs/exceljs/pull/TK">Add pivot table with limitations #TK</a>.
Many thanks to Protobi and <a href="https://github.com/mikez">Michael</a> for this contribution.
</li>
<li>
Merged <a href="https://github.com/exceljs/exceljs/pull/1656">Add TS declarations of Workbook properties #1656</a>.
Many thanks to <a href="https://github.com/kaoths">Tanawit Kritwongwiman</a> for this contribution.
Expand Down Expand Up @@ -163,6 +167,7 @@ To be clear, all contributions added to this library will be included in the lib
</li>
</ul>
</li>
<li><a href="#pivot-tables">Pivot Tables</a></li>
</ul>
</li>
<li><a href="#browser">Browser</a></li>
Expand Down Expand Up @@ -2543,6 +2548,48 @@ workbookReader.on('error', (err) => {
});
```

## Pivot Tables[](#contents)<!-- Link generated with jump2header -->

Add a pivot table to a Workbook without existing pivot tables.

```javascript
worksheet.addPivotTable(configuration);
```

**Note:** Pivot table support is in its early stages with certain limitations, including:

- No support for reading xlsx documents with existing pivot tables (writing is supported).
- Pivot table configurations must consist of 2 rows, 1 column, 1 value, and use the sum metric. The source data can have any number of columns and rows.
- Only one pivot table can be added.

### Add pivot table to worksheet[](#contents)<!-- Link generated with jump2header -->

```javascript
const workbook = new Excel.Workbook();

const worksheet1 = workbook.addWorksheet('Sheet1');
worksheet1.addRows([
['A', 'B', 'C', 'D', 'E'],
['a1', 'b1', 'c1', 4, 5],
['a1', 'b2', 'c1', 4, 5],
['a2', 'b1', 'c2', 14, 24],
['a2', 'b2', 'c2', 24, 35],
['a3', 'b1', 'c3', 34, 45],
['a3', 'b2', 'c3', 44, 45],
]);

const worksheet2 = workbook.addWorksheet('Sheet2');
worksheet2.addPivotTable({
// Source data: entire sheet range
sourceSheet: worksheet1,
// Pivot table fields: via header row in `worksheet1`
rows: ['A', 'B'], // Exactly 2 fields
columns: ['C'], // Exactly 1 field
values: ['E'], // Exactly 1 field
metric: 'sum', // Metric: 'sum' only
});
```

# Browser[](#contents)<!-- Link generated with jump2header -->

A portion of this library has been isolated and tested for use within a browser environment.
Expand Down
3 changes: 3 additions & 0 deletions lib/doc/workbook.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class Workbook {
this.title = '';
this.views = [];
this.media = [];
this.pivotTables = [];
this._definedNames = new DefinedNames();
}

Expand Down Expand Up @@ -174,6 +175,7 @@ class Workbook {
contentStatus: this.contentStatus,
themes: this._themes,
media: this.media,
pivotTables: this.pivotTables,
calcProperties: this.calcProperties,
};
}
Expand Down Expand Up @@ -215,6 +217,7 @@ class Workbook {
this.views = value.views;
this._themes = value.themes;
this.media = value.media || [];
this.pivotTables = value.pivotTables || [];
}
}

Expand Down
141 changes: 141 additions & 0 deletions lib/doc/worksheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const Table = require('./table');
const DataValidations = require('./data-validations');
const Encryptor = require('../utils/encryptor');
const {copyStyle} = require('../utils/copy-style');
const {objectFromProps} = require('../utils/utils');

// Worksheet requirements
// Operate as sheet inside workbook or standalone
Expand Down Expand Up @@ -124,6 +125,8 @@ class Worksheet {
// for tables
this.tables = {};

this.pivotTables = [];

this.conditionalFormattings = [];
}

Expand Down Expand Up @@ -806,6 +809,142 @@ class Worksheet {
return Object.values(this.tables);
}

// =========================================================================
// Pivot Tables
addPivotTable(model) {
// Example `model`:
// {
// // Source of data: the entire sheet range is taken,
// // akin to `worksheet1.getSheetValues()`.
// sourceSheet: worksheet1,
//
// // Pivot table fields: values indicate field names;
// // they come from the first row in `worksheet1`.
// rows: ['A', 'B'], // only 2 items possible for now
// columns: ['C'], // only 1 item possible for now
// values: ['E'], // only 1 item possible for now
// metric: 'sum', // only 'sum' possible for now
// }

// Validate
// --------------------------------------------------
if (this.workbook.pivotTables.length === 1) {
throw new Error(
'A pivot table was already added. At this time, ExcelJS supports at most one pivot table per file.'
);
}

if (model.metric && model.metric !== 'sum') {
throw new Error('Only the "sum" metric is supported at this time.');
}

const headerNames = model.sourceSheet.getRow(1).values.slice(1);
const isInHeaderNames = objectFromProps(headerNames, true);
for (const name of [...model.rows, ...model.columns, ...model.values]) {
if (!isInHeaderNames[name]) {
throw new Error(`The header name "${name}" was not found in ${model.sourceSheet.name}.`);
}
}

if (model.rows.length !== 2) {
throw new Error('Exactly 2 rows need to be specified at this time.');
}

if (model.columns.length !== 1) {
throw new Error('Exactly 1 column needs to be specified at this time.');
}

if (model.values.length !== 1) {
throw new Error('Exactly 1 value needs to be specified at this time.');
}

// Translate
// --------------------------------------------------
const {sourceSheet} = model;
let {rows, columns, values} = model;

const cacheFields = sourceSheet._makeCacheFields([...rows, ...columns]);

// let {rows, columns, values} use indices instead of names;
// names can then be accessed via `pivotTable.cacheFields[index].name`.
// *Note*: Using `reduce` as `Object.fromEntries` requires Node 12+;
// ExcelJs is >=8.3.0 (as of 2023-10-08).
const nameToIndex = cacheFields.reduce((result, cacheField, index) => {
result[cacheField.name] = index;
return result;
}, {});
rows = rows.map(row => nameToIndex[row]);
columns = columns.map(column => nameToIndex[column]);
values = values.map(value => nameToIndex[value]);

// form pivot table object
const pivotTable = {
sourceSheet,
rows,
columns,
values,
metric: 'sum',
cacheFields,
// defined in <pivotTableDefinition> of xl/pivotTables/pivotTable1.xml;
// also used in xl/workbook.xml
cacheId: '10',
};

this.pivotTables.push(pivotTable);
this.workbook.pivotTables.push(pivotTable);

return pivotTable;
}

_makeCacheFields(fieldNamesWithSharedItems) {
// Cache fields are used in pivot tables to reference source data.
//
// Example
// -------
// Turn
//
// `this` sheet values [
// ['A', 'B', 'C', 'D', 'E'],
// ['a1', 'b1', 'c1', 4, 5],
// ['a1', 'b2', 'c1', 4, 5],
// ['a2', 'b1', 'c2', 14, 24],
// ['a2', 'b2', 'c2', 24, 35],
// ['a3', 'b1', 'c3', 34, 45],
// ['a3', 'b2', 'c3', 44, 45],
// ];
// fieldNamesWithSharedItems = ['A', 'B', 'C'];
//
// into
//
// [
// { name: 'A', sharedItems: ['a1', 'a2', 'a3'] },
// { name: 'B', sharedItems: ['b1', 'b2'] },
// { name: 'C', sharedItems: ['c1', 'c2', 'c3'] },
// { name: 'D', sharedItems: null },
// { name: 'E', sharedItems: null },
//

const {range, toSortedArray} = require('../utils/utils');

const names = this.getRow(1).values;
const nameToHasSharedItems = objectFromProps(fieldNamesWithSharedItems, true);

const aggregate = columnIndex => {
const columnValues = this.getColumn(columnIndex).values.splice(2);
const columnValuesAsSet = new Set(columnValues);
return toSortedArray(columnValuesAsSet);
};

// make result
const result = [];
for (const columnIndex of range(1, names.length)) {
const name = names[columnIndex];
const sharedItems = nameToHasSharedItems[name] ? aggregate(columnIndex) : null;
result.push({name, sharedItems});
}
return result;
}

// ===========================================================================
// Conditional Formatting
addConditionalFormatting(cf) {
Expand Down Expand Up @@ -854,6 +993,7 @@ class Worksheet {
media: this._media.map(medium => medium.model),
sheetProtection: this.sheetProtection,
tables: Object.values(this.tables).map(table => table.model),
pivotTables: this.pivotTables,
conditionalFormattings: this.conditionalFormattings,
};

Expand Down Expand Up @@ -920,6 +1060,7 @@ class Worksheet {
tables[table.name] = t;
return tables;
}, {});
this.pivotTables = value.pivotTables;
this.conditionalFormattings = value.conditionalFormattings;
}
}
Expand Down
35 changes: 34 additions & 1 deletion lib/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,11 @@ const utils = {
},
inherits,
dateToExcel(d, date1904) {
return 25569 + ( d.getTime() / (24 * 3600 * 1000) ) - (date1904 ? 1462 : 0);
// eslint-disable-next-line no-mixed-operators
return 25569 + d.getTime() / (24 * 3600 * 1000) - (date1904 ? 1462 : 0);
},
excelToDate(v, date1904) {
// eslint-disable-next-line no-mixed-operators
const millisecondSinceEpoch = Math.round((v - 25569 + (date1904 ? 1462 : 0)) * 24 * 3600 * 1000);
return new Date(millisecondSinceEpoch);
},
Expand Down Expand Up @@ -167,6 +169,37 @@ const utils = {
parseBoolean(value) {
return value === true || value === 'true' || value === 1 || value === '1';
},

*range(start, stop, step = 1) {
const compareOrder = step > 0 ? (a, b) => a < b : (a, b) => a > b;
for (let value = start; compareOrder(value, stop); value += step) {
yield value;
}
},

toSortedArray(values) {
const result = Array.from(values);

// Note: per default, `Array.prototype.sort()` converts values
// to strings when comparing. Here, if we have numbers, we use
// numeric sort.
if (result.every(item => Number.isFinite(item))) {
const compareNumbers = (a, b) => a - b;
return result.sort(compareNumbers);
}

return result.sort();
},

objectFromProps(props, value = null) {
// *Note*: Using `reduce` as `Object.fromEntries` requires Node 12+;
// ExcelJs is >=8.3.0 (as of 2023-10-08).
// return Object.fromEntries(props.map(property => [property, value]));
return props.reduce((result, property) => {
result[property] = value;
return result;
}, {});
},
};

module.exports = utils;
15 changes: 7 additions & 8 deletions lib/xlsx/rel-type.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
'use strict';

module.exports = {
OfficeDocument:
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
OfficeDocument: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
Worksheet: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',
CalcChain: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/calcChain',
SharedStrings:
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
SharedStrings: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
Styles: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
Theme: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
Hyperlink: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
Image: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
CoreProperties:
'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
ExtenderProperties:
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
CoreProperties: 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
ExtenderProperties: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
Comments: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
VmlDrawing: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
Table: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/table',
PivotCacheDefinition: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition',
PivotCacheRecords: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheRecords',
PivotTable: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable',
};
29 changes: 29 additions & 0 deletions lib/xlsx/xform/book/workbook-pivot-cache-xform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const BaseXform = require('../base-xform');

class WorkbookPivotCacheXform extends BaseXform {
render(xmlStream, model) {
xmlStream.leafNode('pivotCache', {
cacheId: model.cacheId,
'r:id': model.rId,
});
}

parseOpen(node) {
if (node.name === 'pivotCache') {
this.model = {
cacheId: node.attributes.cacheId,
rId: node.attributes['r:id'],
};
return true;
}
return false;
}

parseText() {}

parseClose() {
return false;
}
}

module.exports = WorkbookPivotCacheXform;

0 comments on commit f84aaf5

Please sign in to comment.