excellentexport 3.9.11 → 3.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils.ts CHANGED
@@ -1,145 +1,209 @@
1
-
2
- export const b64toBlob = function (b64Data:string, contentType:string, sliceSize?:number): Blob {
3
- // function taken from http://stackoverflow.com/a/16245768/2591950
4
- // author Jeremy Banks http://stackoverflow.com/users/1114/jeremy-banks
5
- contentType = contentType || '';
6
- sliceSize = sliceSize || 512;
7
-
8
- const byteCharacters = atob(b64Data);
9
- const byteArrays = [];
10
-
11
- for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
12
- const slice = byteCharacters.slice(offset, offset + sliceSize);
13
-
14
- const byteNumbers = new Array(slice.length);
15
- for (let i = 0; i < slice.length; i = i + 1) {
16
- byteNumbers[i] = slice.charCodeAt(i);
17
- }
18
-
19
- const byteArray = new Uint8Array(byteNumbers);
20
-
21
- byteArrays.push(byteArray);
22
- }
23
-
24
- return new Blob(byteArrays, {
25
- type: contentType
26
- });
27
- };
28
-
29
- export const templates = {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>'};
30
-
31
- /**
32
- * Convert a string to Base64.
33
- */
34
- export const base64 = function(s:string) : string {
35
- return btoa(unescape(encodeURIComponent(s)));
36
- };
37
-
38
- export const format = function(s:string, context:any) : string {
39
- return s.replace(new RegExp("{(\\w+)}", "g"), function(m, p) {
40
- return context[p] || "{" + p + "}";
41
- });
42
- };
43
-
44
- /**
45
- * Get element by ID.
46
- * @param {*} element
47
- */
48
- export const getTable = function(element :(HTMLTableElement|string)) : HTMLTableElement {
49
- if (typeof element === 'string') {
50
- return document.getElementById(element) as HTMLTableElement;
51
- }
52
- return element;
53
- };
54
-
55
- /**
56
- * Get element by ID.
57
- * @param {*} element
58
- */
59
- export const getAnchor = function(element :(HTMLAnchorElement|string)) : HTMLAnchorElement {
60
- if (typeof element === 'string') {
61
- return document.getElementById(element) as HTMLAnchorElement;
62
- }
63
- return element;
64
- };
65
-
66
- /**
67
- * Encode a value for CSV.
68
- * @param {*} value
69
- */
70
- export const fixCSVField = function(value:string, csvDelimiter:string) : string {
71
- let fixedValue = value;
72
- const addQuotes = (value.indexOf(csvDelimiter) !== -1) || (value.indexOf('\r') !== -1) || (value.indexOf('\n') !== -1);
73
- const replaceDoubleQuotes = (value.indexOf('"') !== -1);
74
-
75
- if (replaceDoubleQuotes) {
76
- fixedValue = fixedValue.replace(/"/g, '""');
77
- }
78
- if (addQuotes || replaceDoubleQuotes) {
79
- fixedValue = '"' + fixedValue + '"';
80
- }
81
-
82
- return fixedValue;
83
- };
84
-
85
- export const tableToArray = function(table:HTMLTableElement) : any[][] {
86
- let tableInfo = Array.prototype.map.call(table.querySelectorAll('tr'), function(tr) {
87
- return Array.prototype.map.call(tr.querySelectorAll('th,td'), function(td) {
88
- return td.innerHTML;
89
- });
90
- });
91
- return tableInfo;
92
- };
93
-
94
- export const tableToCSV = function(table:HTMLTableElement, csvDelimiter:string = ',', csvNewLine:string = '\n') : string {
95
- let data = "";
96
- for (let i = 0; i < table.rows.length; i=i+1) {
97
- const row = table.rows[i];
98
- for (let j = 0; j < row.cells.length; j=j+1) {
99
- const col = row.cells[j];
100
- data = data + (j ? csvDelimiter : '') + fixCSVField(col.textContent.trim(), csvDelimiter);
101
- }
102
- data = data + csvNewLine;
103
- }
104
- return data;
105
- };
106
-
107
- export const createDownloadLink = function(anchor:HTMLAnchorElement, base64data:string, exporttype:string, filename:string) : boolean {
108
- if (window.navigator.msSaveBlob) {
109
- const blob = b64toBlob(base64data, exporttype);
110
- window.navigator.msSaveBlob(blob, filename);
111
- return false;
112
- } else if (window.URL.createObjectURL) {
113
- const blob = b64toBlob(base64data, exporttype);
114
- anchor.href = window.URL.createObjectURL(blob);
115
- } else {
116
- anchor.download = filename;
117
- anchor.href = "data:" + exporttype + ";base64," + base64data;
118
- }
119
-
120
- // Return true to allow the link to work
121
- return true;
122
- };
123
-
124
- // String to ArrayBuffer
125
- export const string2ArrayBuffer = function (s:string): ArrayBuffer {
126
- let buf = new ArrayBuffer(s.length);
127
- let view = new Uint8Array(buf);
128
- for (let i=0; i !== s.length; ++i) {
129
- view[i] = s.charCodeAt(i) & 0xFF;
130
- }
131
- return buf;
132
- };
133
-
134
- export const removeColumns = function(dataArray:any[][], columnIndexes:number[]) {
135
- const uniqueIndexes = [...new Set(columnIndexes)].sort().reverse();
136
- uniqueIndexes.forEach(function(columnIndex) {
137
- dataArray.forEach(function(row) {
138
- row.splice(columnIndex, 1);
139
- });
140
- });
141
- };
142
-
143
- export const hasContent = function(value:any) : boolean {
144
- return value !== undefined && value !== null && value !== "";
1
+
2
+ export const b64toBlob = function (b64Data:string, contentType:string, sliceSize?:number): Blob {
3
+ // function taken from http://stackoverflow.com/a/16245768/2591950
4
+ // author Jeremy Banks http://stackoverflow.com/users/1114/jeremy-banks
5
+ contentType = contentType || '';
6
+ sliceSize = sliceSize || 512;
7
+
8
+ const byteCharacters = atob(b64Data);
9
+ const byteArrays = [];
10
+
11
+ for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
12
+ const slice = byteCharacters.slice(offset, offset + sliceSize);
13
+
14
+ const byteNumbers = new Array(slice.length);
15
+ for (let i = 0; i < slice.length; i = i + 1) {
16
+ byteNumbers[i] = slice.charCodeAt(i);
17
+ }
18
+
19
+ const byteArray = new Uint8Array(byteNumbers);
20
+
21
+ byteArrays.push(byteArray);
22
+ }
23
+
24
+ return new Blob(byteArrays, {
25
+ type: contentType
26
+ });
27
+ };
28
+
29
+ export const templates = {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>'};
30
+
31
+ /**
32
+ * Convert a string to Base64.
33
+ */
34
+ export const base64 = function(s:string) : string {
35
+ return btoa(unescape(encodeURIComponent(s)));
36
+ };
37
+
38
+ export const format = function(s:string, context:any) : string {
39
+ return s.replace(new RegExp("{(\\w+)}", "g"), function(m, p) {
40
+ return context[p] || "{" + p + "}";
41
+ });
42
+ };
43
+
44
+ /**
45
+ * Get element by ID.
46
+ * @param {*} element
47
+ */
48
+ export const getTable = function(element :(HTMLTableElement|string)) : HTMLTableElement {
49
+ if (typeof element === 'string') {
50
+ return document.getElementById(element) as HTMLTableElement;
51
+ }
52
+ return element;
53
+ };
54
+
55
+ /**
56
+ * Get element by ID.
57
+ * @param {*} element
58
+ */
59
+ export const getAnchor = function(element :(HTMLAnchorElement|string)) : HTMLAnchorElement {
60
+ if (typeof element === 'string') {
61
+ return document.getElementById(element) as HTMLAnchorElement;
62
+ }
63
+ return element;
64
+ };
65
+
66
+ /**
67
+ * Encode a value for CSV.
68
+ * @param {*} value
69
+ */
70
+ export const fixCSVField = function(value:string, csvDelimiter:string) : string {
71
+ let fixedValue = value;
72
+ const addQuotes = (value.indexOf(csvDelimiter) !== -1) || (value.indexOf('\r') !== -1) || (value.indexOf('\n') !== -1);
73
+ const replaceDoubleQuotes = (value.indexOf('"') !== -1);
74
+
75
+ if (replaceDoubleQuotes) {
76
+ fixedValue = fixedValue.replace(/"/g, '""');
77
+ }
78
+ if (addQuotes || replaceDoubleQuotes) {
79
+ fixedValue = '"' + fixedValue + '"';
80
+ }
81
+
82
+ return fixedValue;
83
+ };
84
+
85
+ /**
86
+ * Parse an HTML table into a data array and a list of merge ranges,
87
+ * honouring colspan and rowspan attributes.
88
+ */
89
+ export const parseTable = function(table: HTMLTableElement): { data: any[][], merges: {s: {r: number, c: number}, e: {r: number, c: number}}[] } {
90
+ const rows = Array.prototype.slice.call(table.querySelectorAll('tr')) as HTMLTableRowElement[];
91
+ const numRows = rows.length;
92
+
93
+ // grid[r][c] holds the cell value; undefined means "not yet placed"
94
+ const grid: any[][] = [];
95
+ // occupied[r][c] = true when the slot has been claimed by a span
96
+ const occupied: boolean[][] = [];
97
+ const merges: {s: {r: number, c: number}, e: {r: number, c: number}}[] = [];
98
+
99
+ for (let r = 0; r < numRows; r++) {
100
+ if (!grid[r]) grid[r] = [];
101
+ if (!occupied[r]) occupied[r] = [];
102
+
103
+ const cells = Array.prototype.slice.call(rows[r].querySelectorAll('th,td')) as HTMLTableCellElement[];
104
+ let c = 0;
105
+
106
+ cells.forEach(function(cell) {
107
+ // Advance past columns already occupied by a previous rowspan
108
+ while (occupied[r] && occupied[r][c]) {
109
+ c++;
110
+ }
111
+
112
+ const colspan = cell.colSpan || 1;
113
+ const rowspan = cell.rowSpan || 1;
114
+ const value = cell.innerHTML;
115
+
116
+ grid[r][c] = value;
117
+
118
+ // Mark all spanned cells as occupied
119
+ for (let dr = 0; dr < rowspan; dr++) {
120
+ for (let dc = 0; dc < colspan; dc++) {
121
+ if (!occupied[r + dr]) occupied[r + dr] = [];
122
+ occupied[r + dr][c + dc] = true;
123
+ }
124
+ }
125
+
126
+ // Record the merge range when spanning more than one cell
127
+ if (colspan > 1 || rowspan > 1) {
128
+ merges.push({
129
+ s: { r: r, c: c },
130
+ e: { r: r + rowspan - 1, c: c + colspan - 1 }
131
+ });
132
+ }
133
+
134
+ c += colspan;
135
+ });
136
+ }
137
+
138
+ // Normalise grid to a rectangular array
139
+ let numCols = 0;
140
+ grid.forEach(function(row) { if (row.length > numCols) numCols = row.length; });
141
+ const data = grid.map(function(row) {
142
+ return Array.from({ length: numCols }, function(_, i) {
143
+ return row[i] !== undefined ? row[i] : '';
144
+ });
145
+ });
146
+
147
+ return { data, merges };
148
+ };
149
+
150
+ export const tableToArray = function(table:HTMLTableElement) : any[][] {
151
+ return parseTable(table).data;
152
+ };
153
+
154
+ export const tableToMerges = function(table:HTMLTableElement) : {s: {r: number, c: number}, e: {r: number, c: number}}[] {
155
+ return parseTable(table).merges;
156
+ };
157
+
158
+ export const tableToCSV = function(table:HTMLTableElement, csvDelimiter:string = ',', csvNewLine:string = '\n') : string {
159
+ let data = "";
160
+ for (let i = 0; i < table.rows.length; i=i+1) {
161
+ const row = table.rows[i];
162
+ for (let j = 0; j < row.cells.length; j=j+1) {
163
+ const col = row.cells[j];
164
+ data = data + (j ? csvDelimiter : '') + fixCSVField(col.textContent.trim(), csvDelimiter);
165
+ }
166
+ data = data + csvNewLine;
167
+ }
168
+ return data;
169
+ };
170
+
171
+ export const createDownloadLink = function(anchor:HTMLAnchorElement, base64data:string, exporttype:string, filename:string) : boolean {
172
+ if (window.navigator.msSaveBlob) {
173
+ const blob = b64toBlob(base64data, exporttype);
174
+ window.navigator.msSaveBlob(blob, filename);
175
+ return false;
176
+ } else if (window.URL.createObjectURL) {
177
+ const blob = b64toBlob(base64data, exporttype);
178
+ anchor.href = window.URL.createObjectURL(blob);
179
+ } else {
180
+ anchor.download = filename;
181
+ anchor.href = "data:" + exporttype + ";base64," + base64data;
182
+ }
183
+
184
+ // Return true to allow the link to work
185
+ return true;
186
+ };
187
+
188
+ // String to ArrayBuffer
189
+ export const string2ArrayBuffer = function (s:string): ArrayBuffer {
190
+ let buf = new ArrayBuffer(s.length);
191
+ let view = new Uint8Array(buf);
192
+ for (let i=0; i !== s.length; ++i) {
193
+ view[i] = s.charCodeAt(i) & 0xFF;
194
+ }
195
+ return buf;
196
+ };
197
+
198
+ export const removeColumns = function(dataArray:any[][], columnIndexes:number[]) {
199
+ const uniqueIndexes = [...new Set(columnIndexes)].sort().reverse();
200
+ uniqueIndexes.forEach(function(columnIndex) {
201
+ dataArray.forEach(function(row) {
202
+ row.splice(columnIndex, 1);
203
+ });
204
+ });
205
+ };
206
+
207
+ export const hasContent = function(value:any) : boolean {
208
+ return value !== undefined && value !== null && value !== "";
145
209
  }
@@ -1,16 +1,17 @@
1
- const assert = require('assert');
2
-
3
- import ExcellentExport from '../src/excellentexport';
4
- const pkg = require('../package.json');
5
-
6
- describe('version() API', function() {
7
- describe('get version', function() {
8
- it('should get the current version number', function() {
9
- const version = ExcellentExport.version();
10
-
11
- assert.ok(version, 'Version must be returned');
12
- assert.equal(pkg.version, version, "Version must be " + pkg.version);
13
- });
14
- });
15
- });
16
-
1
+ import { describe, expect, test, beforeEach, it, assert } from 'vitest'
2
+
3
+ import ExcellentExport from '../src/excellentexport';
4
+
5
+ import pkg from '../package.json';
6
+
7
+ describe('version() API', function() {
8
+ describe('get version', function() {
9
+ it('should get the current version number', function() {
10
+ const version = ExcellentExport.version();
11
+
12
+ assert.ok(version, 'Version must be returned');
13
+ assert.equal(pkg.version, version, "Version must be " + pkg.version);
14
+ });
15
+ });
16
+ });
17
+
@@ -1,70 +1,70 @@
1
-
2
- import 'expect-puppeteer';
3
-
4
- import ExcellentExport, { ConvertOptions, SheetOptions } from '../src/excellentexport';
5
-
6
-
7
- describe('convert() API', function() {
8
- describe('test sheet options', function() {
9
-
10
- beforeEach(() => {
11
- window.URL.createObjectURL = () => "blob:fake_URL";
12
-
13
- document.body.innerHTML = '';
14
- const element = document.createElement("div");
15
- element.innerHTML =
16
- '<table id="sometable"><tr><th>first</th><th>second</th></tr><tr><td>1234</td><td>123.56</td></tr></table>' +
17
- '<a id="anchor">Link</a>';
18
-
19
- document.body.appendChild(element);
20
- });
21
-
22
- test('filterRowFn', function() {
23
- const options = {
24
- anchor: 'anchor',
25
- filename: 'data_from_table',
26
- format: 'xlsx'
27
- } as ConvertOptions;
28
-
29
- const sheets = [
30
- {
31
- name: 'Sheet Name Here 1',
32
- from: {
33
- table: 'sometable'
34
- },
35
- filterRowFn: (row) => {
36
- if (row[0] === 'first') {
37
- return true;
38
- }
39
- }
40
- }
41
- ] as SheetOptions[];
42
-
43
- const workbook = ExcellentExport.convert(options, sheets);
44
- expect(workbook).not.toBeNull();
45
- });
46
-
47
- test('removeColumns', function() {
48
- const options = {
49
- anchor: 'anchor',
50
- filename: 'data_from_table',
51
- format: 'xlsx'
52
- } as ConvertOptions;
53
-
54
- const sheets = [
55
- {
56
- name: 'Sheet Name Here 1',
57
- from: {
58
- table: 'sometable'
59
- },
60
- removeColumns: [1]
61
- }
62
- ] as SheetOptions[];
63
-
64
- const workbook = ExcellentExport.convert(options, sheets);
65
- expect(workbook).not.toBeNull();
66
- });
67
-
68
- });
69
- });
70
-
1
+
2
+ import { describe, expect, test, beforeEach, it, assert } from 'vitest'
3
+
4
+ import ExcellentExport, { ConvertOptions, SheetOptions } from '../src/excellentexport';
5
+
6
+
7
+ describe('convert() API', function() {
8
+ describe('test sheet options', function() {
9
+
10
+ beforeEach(() => {
11
+ window.URL.createObjectURL = () => "blob:fake_URL";
12
+
13
+ document.body.innerHTML = '';
14
+ const element = document.createElement("div");
15
+ element.innerHTML =
16
+ '<table id="sometable"><tr><th>first</th><th>second</th></tr><tr><td>1234</td><td>123.56</td></tr></table>' +
17
+ '<a id="anchor">Link</a>';
18
+
19
+ document.body.appendChild(element);
20
+ });
21
+
22
+ test('filterRowFn', function() {
23
+ const options = {
24
+ anchor: 'anchor',
25
+ filename: 'data_from_table',
26
+ format: 'xlsx'
27
+ } as ConvertOptions;
28
+
29
+ const sheets = [
30
+ {
31
+ name: 'Sheet Name Here 1',
32
+ from: {
33
+ table: 'sometable'
34
+ },
35
+ filterRowFn: (row) => {
36
+ if (row[0] === 'first') {
37
+ return true;
38
+ }
39
+ }
40
+ }
41
+ ] as SheetOptions[];
42
+
43
+ const workbook = ExcellentExport.convert(options, sheets);
44
+ expect(workbook).not.toBeNull();
45
+ });
46
+
47
+ test('removeColumns', function() {
48
+ const options = {
49
+ anchor: 'anchor',
50
+ filename: 'data_from_table',
51
+ format: 'xlsx'
52
+ } as ConvertOptions;
53
+
54
+ const sheets = [
55
+ {
56
+ name: 'Sheet Name Here 1',
57
+ from: {
58
+ table: 'sometable'
59
+ },
60
+ removeColumns: [1]
61
+ }
62
+ ] as SheetOptions[];
63
+
64
+ const workbook = ExcellentExport.convert(options, sheets);
65
+ expect(workbook).not.toBeNull();
66
+ });
67
+
68
+ });
69
+ });
70
+