@slickgrid-universal/excel-export 4.0.3 → 4.2.0

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.
@@ -0,0 +1,289 @@
1
+ import type {
2
+ Column,
3
+ ExcelStylesheet,
4
+ Formatter,
5
+ FormatterType,
6
+ GetDataValueCallback,
7
+ GridOption,
8
+ SlickGrid,
9
+ } from '@slickgrid-universal/common';
10
+ import {
11
+ Constants,
12
+ FieldType,
13
+ Formatters,
14
+ getColumnFieldType,
15
+ getValueFromParamsOrFormatterOptions,
16
+ GroupTotalFormatters,
17
+ retrieveFormatterOptions,
18
+ } from '@slickgrid-universal/common';
19
+ import { stripTags } from '@slickgrid-universal/utils';
20
+
21
+ export type ExcelFormatter = object & { id: number; };
22
+
23
+ // define all type of potential excel data function callbacks
24
+ export const getExcelSameInputDataCallback: GetDataValueCallback = (data) => data;
25
+ export const getExcelNumberCallback: GetDataValueCallback = (data, column, excelFormatterId, _excelSheet, gridOptions) => ({
26
+ value: typeof data === 'string' && /\d/g.test(data) ? parseNumberWithFormatterOptions(data, column, gridOptions) : data,
27
+ metadata: { style: excelFormatterId }
28
+ });
29
+
30
+ /** Parse a number which the user might have provided formatter options (for example a user might have provided { decimalSeparator: ',', thousandSeparator: ' '}) */
31
+ export function parseNumberWithFormatterOptions(value: any, column: Column, gridOptions: GridOption) {
32
+ let outValue = value;
33
+ if (typeof value === 'string' && value) {
34
+ const decimalSeparator = getValueFromParamsOrFormatterOptions('decimalSeparator', column, gridOptions, Constants.DEFAULT_NUMBER_DECIMAL_SEPARATOR);
35
+ const val: number | string = (decimalSeparator === ',')
36
+ ? parseFloat(value.replace(/[^0-9\,\-]+/g, '').replace(',', '.'))
37
+ : parseFloat(value.replace(/[^\d\.\-]/g, ''));
38
+ outValue = isNaN(val) ? value : val;
39
+ }
40
+ return outValue;
41
+ }
42
+
43
+ /** use different Excel Stylesheet Format as per the Field Type */
44
+ export function useCellFormatByFieldType(stylesheet: ExcelStylesheet, stylesheetFormatters: any, columnDef: Column, grid: SlickGrid, autoDetect = true) {
45
+ const fieldType = getColumnFieldType(columnDef);
46
+ let stylesheetFormatterId: number | undefined;
47
+ let callback: GetDataValueCallback = getExcelSameInputDataCallback;
48
+
49
+ if (fieldType === FieldType.number && autoDetect) {
50
+ stylesheetFormatterId = getExcelFormatFromGridFormatter(stylesheet, stylesheetFormatters, columnDef, grid, 'cell').stylesheetFormatter.id;
51
+ callback = getExcelNumberCallback;
52
+ }
53
+ return { stylesheetFormatterId, getDataValueParser: callback };
54
+ }
55
+
56
+ export function getGroupTotalValue(totals: any, columnDef: Column, groupType: string) {
57
+ return totals?.[groupType]?.[columnDef.field] ?? 0;
58
+ }
59
+
60
+ /** Get numeric formatter options when defined or use default values (minDecimal, maxDecimal, thousandSeparator, decimalSeparator, wrapNegativeNumber) */
61
+ export function getNumericFormatterOptions(columnDef: Column, grid: SlickGrid, formatterType: FormatterType) {
62
+ let dataType: 'currency' | 'decimal' | 'percent' | 'regular';
63
+
64
+ if (formatterType === 'group') {
65
+ switch (columnDef.groupTotalsFormatter) {
66
+ case GroupTotalFormatters.avgTotalsCurrency:
67
+ case GroupTotalFormatters.avgTotalsDollar:
68
+ case GroupTotalFormatters.sumTotalsCurrency:
69
+ case GroupTotalFormatters.sumTotalsCurrencyColored:
70
+ case GroupTotalFormatters.sumTotalsDollar:
71
+ case GroupTotalFormatters.sumTotalsDollarBold:
72
+ case GroupTotalFormatters.sumTotalsDollarColored:
73
+ case GroupTotalFormatters.sumTotalsDollarColoredBold:
74
+ dataType = 'currency';
75
+ break;
76
+ case GroupTotalFormatters.avgTotalsPercentage:
77
+ dataType = 'percent';
78
+ break;
79
+ case GroupTotalFormatters.avgTotals:
80
+ case GroupTotalFormatters.minTotals:
81
+ case GroupTotalFormatters.maxTotals:
82
+ case GroupTotalFormatters.sumTotals:
83
+ case GroupTotalFormatters.sumTotalsColored:
84
+ case GroupTotalFormatters.sumTotalsBold:
85
+ default:
86
+ // side note, formatters are using "regular" without any decimal limits (min, max),
87
+ // however in Excel export with custom format that doesn't work so well, we should use "decimal" to at least show optional decimals with "##"
88
+ dataType = 'decimal';
89
+ break;
90
+ }
91
+ } else {
92
+ // when formatter is a Formatter.multiple, we need to loop through each of its formatter to find the best numeric data type
93
+ if (columnDef.formatter === Formatters.multiple && Array.isArray(columnDef.params?.formatters)) {
94
+ dataType = 'decimal';
95
+ for (const formatter of columnDef.params.formatters) {
96
+ dataType = getFormatterNumericDataType(formatter);
97
+ if (dataType !== 'decimal') {
98
+ break; // if we found something different than the default (decimal) then we can assume that we found our type so we can stop & return
99
+ }
100
+ }
101
+ } else {
102
+ dataType = getFormatterNumericDataType(columnDef.formatter);
103
+ }
104
+ }
105
+ return retrieveFormatterOptions(columnDef, grid, dataType!, formatterType);
106
+ }
107
+
108
+ export function getFormatterNumericDataType(formatter?: Formatter) {
109
+ let dataType: 'currency' | 'decimal' | 'percent' | 'regular';
110
+
111
+ switch (formatter) {
112
+ case Formatters.currency:
113
+ case Formatters.dollar:
114
+ case Formatters.dollarColored:
115
+ case Formatters.dollarColoredBold:
116
+ dataType = 'currency';
117
+ break;
118
+ case Formatters.percent:
119
+ case Formatters.percentComplete:
120
+ case Formatters.percentCompleteBar:
121
+ case Formatters.percentCompleteBarWithText:
122
+ case Formatters.percentSymbol:
123
+ dataType = 'percent';
124
+ break;
125
+ case Formatters.decimal:
126
+ default:
127
+ // use "decimal" instead of "regular" to show optional decimals "##" in Excel
128
+ dataType = 'decimal';
129
+ break;
130
+ }
131
+ return dataType;
132
+ }
133
+
134
+ export function getExcelFormatFromGridFormatter(stylesheet: ExcelStylesheet, stylesheetFormatters: any, columnDef: Column, grid: SlickGrid, formatterType: FormatterType) {
135
+ let format = '';
136
+ let groupType = '';
137
+ let stylesheetFormatter: undefined | ExcelFormatter;
138
+ const fieldType = getColumnFieldType(columnDef);
139
+
140
+ if (formatterType === 'group') {
141
+ switch (columnDef.groupTotalsFormatter) {
142
+ case GroupTotalFormatters.avgTotals:
143
+ case GroupTotalFormatters.avgTotalsCurrency:
144
+ case GroupTotalFormatters.avgTotalsDollar:
145
+ case GroupTotalFormatters.avgTotalsPercentage:
146
+ groupType = 'avg';
147
+ break;
148
+ case GroupTotalFormatters.minTotals:
149
+ groupType = 'min';
150
+ break;
151
+ case GroupTotalFormatters.maxTotals:
152
+ groupType = 'max';
153
+ break;
154
+ case GroupTotalFormatters.sumTotals:
155
+ case GroupTotalFormatters.sumTotalsBold:
156
+ case GroupTotalFormatters.sumTotalsColored:
157
+ case GroupTotalFormatters.sumTotalsCurrency:
158
+ case GroupTotalFormatters.sumTotalsCurrencyColored:
159
+ case GroupTotalFormatters.sumTotalsDollar:
160
+ case GroupTotalFormatters.sumTotalsDollarColoredBold:
161
+ case GroupTotalFormatters.sumTotalsDollarColored:
162
+ case GroupTotalFormatters.sumTotalsDollarBold:
163
+ groupType = 'sum';
164
+ break;
165
+ default:
166
+ stylesheetFormatter = stylesheetFormatters.numberFormatter;
167
+ break;
168
+ }
169
+ } else {
170
+ switch (fieldType) {
171
+ case FieldType.number:
172
+ switch (columnDef.formatter) {
173
+ case Formatters.multiple:
174
+ // when formatter is a Formatter.multiple, we need to loop through each of its formatter to find the best possible Excel format
175
+ if (Array.isArray(columnDef.params?.formatters)) {
176
+ for (const formatter of columnDef.params.formatters) {
177
+ const { stylesheetFormatter: stylesheetFormatterResult } = getExcelFormatFromGridFormatter(stylesheet, stylesheetFormatters, { ...columnDef, formatter } as Column, grid, formatterType);
178
+ if (stylesheetFormatterResult !== stylesheetFormatters.numberFormatter) {
179
+ stylesheetFormatter = stylesheetFormatterResult;
180
+ break;
181
+ }
182
+ }
183
+ }
184
+ if (!stylesheetFormatter) {
185
+ stylesheetFormatter = stylesheetFormatters.numberFormatter;
186
+ }
187
+ break;
188
+ case Formatters.currency:
189
+ case Formatters.decimal:
190
+ case Formatters.dollar:
191
+ case Formatters.dollarColored:
192
+ case Formatters.dollarColoredBold:
193
+ case Formatters.percent:
194
+ case Formatters.percentComplete:
195
+ case Formatters.percentCompleteBar:
196
+ case Formatters.percentCompleteBarWithText:
197
+ case Formatters.percentSymbol:
198
+ format = createExcelFormatFromGridFormatter(columnDef, grid, 'cell');
199
+ break;
200
+ default:
201
+ stylesheetFormatter = stylesheetFormatters.numberFormatter;
202
+ break;
203
+ }
204
+ break;
205
+ }
206
+ }
207
+
208
+ if (!stylesheetFormatter && (columnDef.formatter || columnDef.groupTotalsFormatter)) {
209
+ format = createExcelFormatFromGridFormatter(columnDef, grid, formatterType, groupType);
210
+ if (!stylesheetFormatters.hasOwnProperty(format)) {
211
+ stylesheetFormatters[format] = stylesheet.createFormat({ format }); // save new formatter with its format as a prop key
212
+ }
213
+ stylesheetFormatter = stylesheetFormatters[format] as ExcelFormatter;
214
+ }
215
+ return { stylesheetFormatter: stylesheetFormatter as ExcelFormatter, groupType };
216
+ }
217
+
218
+ // --
219
+ // private functions
220
+ // ------------------
221
+
222
+ function createFormatFromNumber(formattedVal: string) {
223
+ // full number syntax can have up to 7 sections, for example::
224
+ // Total: ($10,420.55 USD) Expensed
225
+ const [
226
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
227
+ _,
228
+ prefix,
229
+ openBraquet,
230
+ symbolPrefix,
231
+ number,
232
+ symbolSuffix,
233
+ closingBraquet,
234
+ suffix
235
+ ] = formattedVal?.match(/^([^\d\(\-]*)([\(]?)([^\d]*)([\-]?[\w]]?[\d\s]*[.,\d]*[\d]*[^)\s\%]?)([^\d.,)]*)([\)]?)([^\d]*)$/i) || [];
236
+
237
+ // we use 1 so that they won't be removed when rounding numbers, however Excel uses 0 and # symbol
238
+ // replace 1's by 0's (required numbers) and replace 2's by "#" (optional numbers)
239
+ const replacedNumber = (number || '').replace(/1/g, '0').replace(/[2]/g, '#');
240
+
241
+ const format = [
242
+ escapeQuotes(prefix ?? ''),
243
+ openBraquet ?? '',
244
+ escapeQuotes(symbolPrefix ?? ''),
245
+ replacedNumber,
246
+ escapeQuotes(symbolSuffix ?? ''),
247
+ closingBraquet ?? '',
248
+ escapeQuotes(suffix ?? '')
249
+ ].join('');
250
+ return format.replace(',', '\,');
251
+ }
252
+
253
+ function createExcelFormatFromGridFormatter(columnDef: Column, grid: SlickGrid, formatterType: FormatterType, groupType = '') {
254
+ let outputFormat = '';
255
+ let positiveFormat = '';
256
+ let negativeFormat = '';
257
+ const { minDecimal, maxDecimal, thousandSeparator } = getNumericFormatterOptions(columnDef, grid, formatterType);
258
+ const leftInteger = thousandSeparator ? '2220' : '0';
259
+ const testingNo = parseFloat(`${leftInteger}.${excelTestingDecimalNumberPadding(minDecimal, maxDecimal)}`);
260
+
261
+ if (formatterType === 'group' && columnDef.groupTotalsFormatter) {
262
+ positiveFormat = stripTags(columnDef.groupTotalsFormatter({ [groupType]: { [columnDef.field]: testingNo } }, columnDef, grid));
263
+ negativeFormat = stripTags(columnDef.groupTotalsFormatter({ [groupType]: { [columnDef.field]: -testingNo } }, columnDef, grid));
264
+ } else if (columnDef.formatter) {
265
+ positiveFormat = stripTags(columnDef.formatter(0, 0, testingNo, columnDef, {}, grid) as string);
266
+ negativeFormat = stripTags(columnDef.formatter(0, 0, -testingNo, columnDef, {}, grid) as string);
267
+ }
268
+ if (positiveFormat && negativeFormat) {
269
+ outputFormat = createFormatFromNumber(positiveFormat) + ';' + createFormatFromNumber(negativeFormat);
270
+ }
271
+ return outputFormat;
272
+ }
273
+
274
+ function escapeQuotes(val: string) {
275
+ return val ? `"${val}"` : val;
276
+ }
277
+
278
+ /** Get number format for a number cell, for example { minDecimal: 2, maxDecimal: 5 } will return "00###" */
279
+ function excelTestingDecimalNumberPadding(minDecimal: number, maxDecimal: number) {
280
+ return textPadding('1', minDecimal) + textPadding('2', maxDecimal - minDecimal);
281
+ }
282
+
283
+ function textPadding(numberStr: string, count: number): string {
284
+ let output = '';
285
+ for (let i = 0; i < count; i++) {
286
+ output += numberStr;
287
+ }
288
+ return output;
289
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { ExcelExportService } from './excelExport.service';
@@ -0,0 +1,6 @@
1
+ import { ExcelMetadata } from './excelMetadata.interface';
2
+
3
+ export interface ExcelCellFormat {
4
+ value: any;
5
+ metadata: ExcelMetadata;
6
+ }
@@ -0,0 +1,9 @@
1
+ export interface ExcelMetadata {
2
+ alignment?: any;
3
+ border?: any;
4
+ font?: any;
5
+ format?: any;
6
+ style?: any;
7
+ type?: any;
8
+ protection?: any;
9
+ }
@@ -0,0 +1,34 @@
1
+ import { ExcelAlignmentStyle, ExcelBorderStyle, ExcelColorStyle, ExcelCustomStyling, ExcelFillStyle, ExcelFontStyle } from '@slickgrid-universal/common';
2
+
3
+ export interface ExcelStylesheet {
4
+ createBorderFormatter: (border: ExcelBorderStyle) => any;
5
+ createDifferentialStyle: (instructions: ExcelCustomStyling) => any;
6
+ createFill: (instructions: ExcelFillStyle) => any;
7
+ createFontStyle: (instructions: ExcelFontStyle) => any;
8
+ createFormat: (instructions: ExcelCustomStyling) => any;
9
+ createNumberFormatter: (format: string) => any;
10
+ createSimpleFormatter: (type: any) => any;
11
+ createTableStyle: (instructions: any) => any;
12
+ exportAlignment: (doc: any, alignmentData: ExcelAlignmentStyle) => any;
13
+ exportBorder: (doc: any, data: any[]) => ExcelBorderStyle;
14
+ exportBorders: (doc: any) => any;
15
+ exportCellFormatElement: (doc: any, instructions: ExcelCustomStyling) => any;
16
+ exportCellStyles: (doc: any) => any;
17
+ exportColor: (doc: any, color: ExcelColorStyle) => any;
18
+ exportDifferentialStyles: (doc: any) => any;
19
+ exportDFX: (doc: any, style: any) => any;
20
+ exportFill: (doc: any, fd: any) => any;
21
+ exportFills: (doc: any) => any;
22
+ exportFont: (doc: any, fd: any) => any;
23
+ exportFonts: (doc: any) => any;
24
+ exportGradientFill: (doc: any, data: any[]) => any;
25
+ exportNumberFormatter: (doc: any, fd: any) => any;
26
+ exportNumberFormatters: (doc: any) => any;
27
+ exportMasterCellFormats: (doc: any) => any;
28
+ exportMasterCellStyles: (doc: any) => any;
29
+ exportPatternFill: (doc: any, data: any[]) => any;
30
+ exportProtection: (doc: any, protectionData: any) => any;
31
+ exportTableStyle: (doc: any, style: any) => any;
32
+ exportTableStyles: (doc: any) => any;
33
+ toXML: () => any;
34
+ }
@@ -0,0 +1,3 @@
1
+ export * from './excelCellFormat.interface';
2
+ export * from './excelMetadata.interface';
3
+ export * from './excelStylesheet.interface';
@@ -0,0 +1 @@
1
+ declare module 'excel-builder-webpacker';
@@ -0,0 +1 @@
1
+ import 'jest-extended/all';
@@ -0,0 +1,8 @@
1
+ /* SystemJS module definition */
2
+ declare const module: NodeModule;
3
+ interface NodeModule {
4
+ id: string;
5
+ }
6
+ interface window {
7
+ Slicker: any;
8
+ }