@slickgrid-universal/excel-export 5.0.0-beta.2 → 5.0.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.
@@ -1,640 +1,640 @@
1
- import {
2
- downloadExcelFile,
3
- type ExcelColumnMetadata,
4
- type ExcelMetadata,
5
- type StyleSheet,
6
- Workbook,
7
- type Worksheet,
8
- } from 'excel-builder-vanilla';
9
- import type {
10
- Column,
11
- ContainerService,
12
- ExcelExportService as BaseExcelExportService,
13
- ExcelExportOption,
14
- ExternalResource,
15
-
16
- GetDataValueCallback,
17
- GetGroupTotalValueCallback,
18
- GridOption,
19
- KeyTitlePair,
20
- Locale,
21
- PubSubService,
22
- SlickDataView,
23
- SlickGrid,
24
- TranslaterService,
25
- } from '@slickgrid-universal/common';
26
- import {
27
- Constants,
28
- // utility functions
29
- exportWithFormatterWhenDefined,
30
- FieldType,
31
- FileType,
32
- getColumnFieldType,
33
- getTranslationPrefix,
34
- isColumnDateType,
35
- } from '@slickgrid-universal/common';
36
- import { addWhiteSpaces, deepCopy, getHtmlStringOutput, stripTags, titleCase } from '@slickgrid-universal/utils';
37
-
38
- import {
39
- type ExcelFormatter,
40
- getGroupTotalValue,
41
- getExcelFormatFromGridFormatter,
42
- useCellFormatByFieldType,
43
- } from './excelUtils';
44
-
45
- const DEFAULT_EXPORT_OPTIONS: ExcelExportOption = {
46
- filename: 'export',
47
- format: FileType.xlsx
48
- };
49
-
50
- export class ExcelExportService implements ExternalResource, BaseExcelExportService {
51
- protected _fileFormat = FileType.xlsx;
52
- protected _grid!: SlickGrid;
53
- protected _locales!: Locale;
54
- protected _groupedColumnHeaders?: Array<KeyTitlePair>;
55
- protected _columnHeaders: Array<KeyTitlePair> = [];
56
- protected _hasColumnTitlePreHeader = false;
57
- protected _hasGroupedItems = false;
58
- protected _excelExportOptions!: ExcelExportOption;
59
- protected _sheet!: Worksheet;
60
- protected _stylesheet!: StyleSheet;
61
- protected _stylesheetFormats: any;
62
- protected _pubSubService: PubSubService | null = null;
63
- protected _translaterService: TranslaterService | undefined;
64
- protected _workbook!: Workbook;
65
-
66
- // references of each detected cell and/or group total formats
67
- protected _regularCellExcelFormats: { [fieldId: string]: { stylesheetFormatterId?: number; getDataValueParser: GetDataValueCallback; }; } = {};
68
- protected _groupTotalExcelFormats: { [fieldId: string]: { groupType: string; stylesheetFormatter?: ExcelFormatter; getGroupTotalParser?: GetGroupTotalValueCallback; }; } = {};
69
-
70
- /** ExcelExportService class name which is use to find service instance in the external registered services */
71
- readonly className = 'ExcelExportService';
72
-
73
- protected get _datasetIdPropName(): string {
74
- return this._gridOptions?.datasetIdPropertyName ?? 'id';
75
- }
76
-
77
- /** Getter of SlickGrid DataView object */
78
- get _dataView(): SlickDataView {
79
- return this._grid?.getData<SlickDataView>();
80
- }
81
-
82
- /** Getter for the Grid Options pulled through the Grid Object */
83
- protected get _gridOptions(): GridOption {
84
- return this._grid?.getOptions() || {} as GridOption;
85
- }
86
-
87
- get stylesheet() {
88
- return this._stylesheet;
89
- }
90
-
91
- get stylesheetFormats() {
92
- return this._stylesheetFormats;
93
- }
94
-
95
- get groupTotalExcelFormats() {
96
- return this._groupTotalExcelFormats;
97
- }
98
-
99
- get regularCellExcelFormats() {
100
- return this._regularCellExcelFormats;
101
- }
102
-
103
- dispose() {
104
- this._pubSubService?.unsubscribeAll();
105
- }
106
-
107
- /**
108
- * Initialize the Export Service
109
- * @param grid
110
- * @param containerService
111
- */
112
- init(grid: SlickGrid, containerService: ContainerService): void {
113
- this._grid = grid;
114
- this._pubSubService = containerService.get<PubSubService>('PubSubService');
115
-
116
- // get locales provided by user in main file or else use default English locales via the Constants
117
- this._locales = this._gridOptions?.locales ?? Constants.locales;
118
- this._translaterService = this._gridOptions?.translater;
119
-
120
- if (this._gridOptions.enableTranslate && (!this._translaterService || !this._translaterService.translate)) {
121
- throw new Error('[Slickgrid-Universal] requires a Translate Service to be passed in the "translater" Grid Options when "enableTranslate" is enabled. (example: this.gridOptions = { enableTranslate: true, translater: this.translaterService })');
122
- }
123
- }
124
-
125
- /**
126
- * Function to export the Grid result to an Excel CSV format using javascript for it to produce the CSV file.
127
- * This is a WYSIWYG export to file output (What You See is What You Get)
128
- *
129
- * NOTES: The column position needs to match perfectly the JSON Object position because of the way we are pulling the data,
130
- * which means that if any column(s) got moved in the UI, it has to be reflected in the JSON array output as well
131
- *
132
- * Example: exportToExcel({ format: FileType.csv, delimiter: DelimiterType.comma })
133
- */
134
- exportToExcel(options?: ExcelExportOption): Promise<boolean> {
135
- if (!this._grid || !this._dataView || !this._pubSubService) {
136
- throw new Error('[Slickgrid-Universal] it seems that the SlickGrid & DataView objects and/or PubSubService are not initialized did you forget to enable the grid option flag "enableExcelExport"?');
137
- }
138
- this._pubSubService?.publish(`onBeforeExportToExcel`, true);
139
- this._excelExportOptions = deepCopy({ ...DEFAULT_EXPORT_OPTIONS, ...this._gridOptions.excelExportOptions, ...options });
140
- this._fileFormat = this._excelExportOptions.format || FileType.xlsx;
141
-
142
- // reset references of detected Excel formats
143
- this._regularCellExcelFormats = {};
144
- this._groupTotalExcelFormats = {};
145
-
146
- // wrap in a Promise so that we can add loading spinner
147
- return new Promise(resolve => {
148
- // prepare the Excel Workbook & Sheet
149
- // we can use ExcelBuilder constructor with WebPack but we need to use function calls with RequireJS/SystemJS
150
- const worksheetOptions = { name: this._excelExportOptions.sheetName || 'Sheet1' };
151
- this._workbook = new Workbook();
152
- this._sheet = this._workbook.createWorksheet(worksheetOptions);
153
-
154
- // add any Excel Format/Stylesheet to current Workbook
155
- this._stylesheet = this._workbook.getStyleSheet();
156
-
157
- // create some common default Excel formatters that will be used
158
- const boldFormatter = this._stylesheet.createFormat({ font: { bold: true } });
159
- const stringFormatter = this._stylesheet.createFormat({ format: '@' });
160
- const numberFormatter = this._stylesheet.createFormat({ format: '0' });
161
- this._stylesheetFormats = {
162
- boldFormatter,
163
- numberFormatter,
164
- stringFormatter,
165
- };
166
- this._sheet.setColumnFormats([boldFormatter]);
167
-
168
- // get the CSV output from the grid data
169
- const dataOutput = this.getDataOutput();
170
-
171
- // trigger a download file
172
- // wrap it into a setTimeout so that the EventAggregator has enough time to start a pre-process like showing a spinner
173
- setTimeout(async () => {
174
- if (this._gridOptions?.excelExportOptions?.customExcelHeader) {
175
- this._gridOptions.excelExportOptions.customExcelHeader(this._workbook, this._sheet);
176
- }
177
-
178
- const columns = this._grid?.getColumns() || [];
179
- this._sheet.setColumns(this.getColumnStyles(columns));
180
-
181
- const currentSheetData = this._sheet.data;
182
- let finalOutput = currentSheetData;
183
- if (Array.isArray(currentSheetData) && Array.isArray(dataOutput)) {
184
- finalOutput = this._sheet.data.concat(dataOutput);
185
- }
186
-
187
- this._sheet.setData(finalOutput);
188
- this._workbook.addWorksheet(this._sheet);
189
-
190
- // MIME type could be undefined, if that's the case we'll detect the type by its file extension
191
- // user could also provide its own mime type, if however an empty string is provided we will consider to be without any MIME type)
192
- let mimeType = this._excelExportOptions?.mimeType;
193
- if (mimeType === undefined) {
194
- mimeType = this._fileFormat === FileType.xls ? 'application/vnd.ms-excel' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
195
- }
196
-
197
- const filename = `${this._excelExportOptions.filename}.${this._fileFormat}`;
198
- downloadExcelFile(this._workbook, filename, { mimeType }).then(() => {
199
- this._pubSubService?.publish(`onAfterExportToExcel`, { filename, mimeType });
200
- resolve(true);
201
- });
202
- });
203
- });
204
- }
205
-
206
- /**
207
- * Takes a positive integer and returns the corresponding column name.
208
- * dealing with the Excel column position is a bit tricky since the first 26 columns are single char (A,B,...) but after that it becomes double char (AA,AB,...)
209
- * so we must first see if we are in the first section of 26 chars, if that is the case we just concatenate 1 (1st row) so it becomes (A1, B1, ...)
210
- * and again if we go 26, we need to add yet again an extra prefix (AA1, AB1, ...) and so goes the cycle
211
- * @param {number} colIndex - The positive integer to convert to a column name.
212
- * @return {string} The column name.
213
- */
214
- getExcelColumnNameByIndex(colIndex: number): string {
215
- const letters = 'ZABCDEFGHIJKLMNOPQRSTUVWXY';
216
-
217
- let nextPos = Math.floor(colIndex / 26);
218
- const lastPos = Math.floor(colIndex % 26);
219
- if (lastPos === 0) {
220
- nextPos--;
221
- }
222
-
223
- if (colIndex > 26) {
224
- return this.getExcelColumnNameByIndex(nextPos) + letters[lastPos];
225
- }
226
-
227
- return letters[lastPos] + '';
228
- }
229
-
230
- // -----------------------
231
- // protected functions
232
- // -----------------------
233
-
234
- protected getDataOutput(): Array<string[] | ExcelColumnMetadata[]> {
235
- const columns = this._grid?.getColumns() || [];
236
-
237
- // data variable which will hold all the fields data of a row
238
- const outputData: Array<string[] | ExcelColumnMetadata[]> = [];
239
- const gridExportOptions = this._gridOptions?.excelExportOptions;
240
- const columnHeaderStyle = gridExportOptions?.columnHeaderStyle;
241
- let columnHeaderStyleId = this._stylesheetFormats.boldFormatter.id;
242
- if (columnHeaderStyle) {
243
- columnHeaderStyleId = this._stylesheet.createFormat(columnHeaderStyle).id;
244
- }
245
-
246
- // get all Grouped Column Header Titles when defined (from pre-header row)
247
- if (this._gridOptions.createPreHeaderPanel && this._gridOptions.showPreHeaderPanel && !this._gridOptions.enableDraggableGrouping) {
248
- // when having Grouped Header Titles (in the pre-header), then make the cell Bold & Aligned Center
249
- const boldCenterAlign = this._stylesheet.createFormat({ alignment: { horizontal: 'center' }, font: { bold: true } });
250
- outputData.push(this.getColumnGroupedHeaderTitlesData(columns, { style: boldCenterAlign?.id }));
251
- this._hasColumnTitlePreHeader = true;
252
- }
253
-
254
- // get all Column Header Titles (it might include a "Group by" title at A1 cell)
255
- // also style the headers, defaults to Bold but user could pass his own style
256
- outputData.push(this.getColumnHeaderData(columns, { style: columnHeaderStyleId }));
257
-
258
- // Populate the rest of the Grid Data
259
- this.pushAllGridRowDataToArray(outputData, columns);
260
-
261
- return outputData;
262
- }
263
-
264
- /** Get each column style including a style for the width of each column */
265
- protected getColumnStyles(columns: Column[]): any[] {
266
- const grouping = this._dataView.getGrouping();
267
- const columnStyles = [];
268
- if (Array.isArray(grouping) && grouping.length > 0) {
269
- columnStyles.push({
270
- bestFit: true,
271
- columnStyles: this._gridOptions?.excelExportOptions?.customColumnWidth ?? 10
272
- });
273
- }
274
-
275
- columns.forEach((columnDef: Column) => {
276
- const skippedField = columnDef.excludeFromExport ?? false;
277
- // if column width is 0, then we consider that field as a hidden field and should not be part of the export
278
- if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
279
- columnStyles.push({
280
- bestFit: true,
281
- width: columnDef.excelExportOptions?.width ?? this._gridOptions?.excelExportOptions?.customColumnWidth ?? 10
282
- });
283
- }
284
- });
285
- return columnStyles;
286
- }
287
-
288
- /**
289
- * Get all Grouped Header Titles and their keys, translate the title when required, and format them in Bold
290
- * @param {Array<Object>} columns - grid column definitions
291
- * @param {Object} metadata - Excel metadata
292
- * @returns {Object} array of Excel cell format
293
- */
294
- protected getColumnGroupedHeaderTitlesData(columns: Column[], metadata: ExcelMetadata): Array<ExcelColumnMetadata> {
295
- let outputGroupedHeaderTitles: Array<ExcelColumnMetadata> = [];
296
-
297
- // get all Column Header Titles
298
- this._groupedColumnHeaders = this.getColumnGroupedHeaderTitles(columns) || [];
299
- if (this._groupedColumnHeaders && Array.isArray(this._groupedColumnHeaders) && this._groupedColumnHeaders.length > 0) {
300
- // add the header row + add a new line at the end of the row
301
- outputGroupedHeaderTitles = this._groupedColumnHeaders.map((header) => ({ value: header.title, metadata }));
302
- }
303
-
304
- // merge necessary cells (any grouped header titles)
305
- let colspanStartIndex = 0;
306
- const headersLn = this._groupedColumnHeaders.length;
307
- for (let cellIndex = 0; cellIndex < headersLn; cellIndex++) {
308
- if ((cellIndex + 1) === headersLn || ((cellIndex + 1) < headersLn && this._groupedColumnHeaders[cellIndex].title !== this._groupedColumnHeaders[cellIndex + 1].title)) {
309
- const leftExcelColumnChar = this.getExcelColumnNameByIndex(colspanStartIndex + 1);
310
- const rightExcelColumnChar = this.getExcelColumnNameByIndex(cellIndex + 1);
311
- this._sheet.mergeCells(`${leftExcelColumnChar}1`, `${rightExcelColumnChar}1`);
312
-
313
- // next group starts 1 column index away
314
- colspanStartIndex = cellIndex + 1;
315
- }
316
- }
317
-
318
- return outputGroupedHeaderTitles;
319
- }
320
-
321
- /** Get all column headers and format them in Bold */
322
- protected getColumnHeaderData(columns: Column[], metadata: ExcelMetadata): Array<ExcelColumnMetadata> {
323
- let outputHeaderTitles: Array<ExcelColumnMetadata> = [];
324
-
325
- // get all Column Header Titles
326
- this._columnHeaders = this.getColumnHeaders(columns) || [];
327
- if (this._columnHeaders && Array.isArray(this._columnHeaders) && this._columnHeaders.length > 0) {
328
- // add the header row + add a new line at the end of the row
329
- outputHeaderTitles = this._columnHeaders.map((header) => ({ value: stripTags(header.title), metadata }));
330
- }
331
-
332
- // do we have a Group by title?
333
- const groupTitle = this.getGroupColumnTitle();
334
- if (groupTitle) {
335
- outputHeaderTitles.unshift({ value: groupTitle, metadata });
336
- }
337
-
338
- return outputHeaderTitles;
339
- }
340
-
341
- protected getGroupColumnTitle(): string | null {
342
- // Group By text, it could be set in the export options or from translation or if nothing is found then use the English constant text
343
- let groupByColumnHeader = this._excelExportOptions.groupingColumnHeaderTitle;
344
- if (!groupByColumnHeader && this._gridOptions.enableTranslate && this._translaterService?.translate) {
345
- groupByColumnHeader = this._translaterService.translate(`${getTranslationPrefix(this._gridOptions)}GROUP_BY`);
346
- } else if (!groupByColumnHeader) {
347
- groupByColumnHeader = this._locales && this._locales.TEXT_GROUP_BY;
348
- }
349
-
350
- // get grouped column titles and if found, we will add a "Group by" column at the first column index
351
- // if it's a CSV format, we'll escape the text in double quotes
352
- const grouping = this._dataView.getGrouping();
353
- if (Array.isArray(grouping) && grouping.length > 0) {
354
- this._hasGroupedItems = true;
355
- return groupByColumnHeader;
356
- } else {
357
- this._hasGroupedItems = false;
358
- }
359
- return null;
360
- }
361
-
362
- /**
363
- * Get all Grouped Header Titles and their keys, translate the title when required.
364
- * @param {Array<object>} columns of the grid
365
- */
366
- protected getColumnGroupedHeaderTitles(columns: Column[]): Array<KeyTitlePair> {
367
- const groupedColumnHeaders: Array<KeyTitlePair> = [];
368
-
369
- if (columns && Array.isArray(columns)) {
370
- // Populate the Grouped Column Header, pull the columnGroup(Key) defined
371
- columns.forEach((columnDef) => {
372
- let groupedHeaderTitle = '';
373
- if (columnDef.columnGroupKey && this._gridOptions.enableTranslate && this._translaterService?.translate) {
374
- groupedHeaderTitle = this._translaterService.translate(columnDef.columnGroupKey);
375
- } else {
376
- groupedHeaderTitle = columnDef.columnGroup || '';
377
- }
378
- const skippedField = columnDef.excludeFromExport || false;
379
-
380
- // if column width is 0px, then we consider that field as a hidden field and should not be part of the export
381
- if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
382
- groupedColumnHeaders.push({
383
- key: (columnDef.field || columnDef.id) as string,
384
- title: groupedHeaderTitle || ''
385
- });
386
- }
387
- });
388
- }
389
- return groupedColumnHeaders;
390
- }
391
-
392
- /**
393
- * Get all header titles and their keys, translate the title when required.
394
- * @param {Array<object>} columns of the grid
395
- */
396
- protected getColumnHeaders(columns: Column[]): Array<KeyTitlePair> | null {
397
- const columnHeaders: Array<KeyTitlePair> = [];
398
-
399
- if (columns && Array.isArray(columns)) {
400
- // Populate the Column Header, pull the name defined
401
- columns.forEach((columnDef) => {
402
- let headerTitle = '';
403
- if ((columnDef.nameKey || columnDef.nameKey) && this._gridOptions.enableTranslate && this._translaterService?.translate) {
404
- headerTitle = this._translaterService.translate((columnDef.nameKey || columnDef.nameKey));
405
- } else {
406
- headerTitle = getHtmlStringOutput(columnDef.name || '', 'innerHTML') || titleCase(columnDef.field);
407
- }
408
- const skippedField = columnDef.excludeFromExport || false;
409
-
410
- // if column width is 0, then we consider that field as a hidden field and should not be part of the export
411
- if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
412
- columnHeaders.push({
413
- key: (columnDef.field || columnDef.id) + '',
414
- title: headerTitle
415
- });
416
- }
417
- });
418
- }
419
- return columnHeaders;
420
- }
421
-
422
- /**
423
- * Get all the grid row data and return that as an output string
424
- */
425
- protected pushAllGridRowDataToArray(originalDaraArray: Array<Array<string | ExcelColumnMetadata | number>>, columns: Column[]): Array<Array<string | ExcelColumnMetadata | number>> {
426
- const lineCount = this._dataView.getLength();
427
-
428
- // loop through all the grid rows of data
429
- for (let rowNumber = 0; rowNumber < lineCount; rowNumber++) {
430
- const itemObj = this._dataView.getItem(rowNumber);
431
-
432
- // make sure we have a filled object AND that the item doesn't include the "getItem" method
433
- // this happen could happen with an opened Row Detail as it seems to include an empty Slick DataView (we'll just skip those lines)
434
- if (itemObj && !itemObj.hasOwnProperty('getItem')) {
435
- // Normal row (not grouped by anything) would have an ID which was predefined in the Grid Columns definition
436
- if (itemObj[this._datasetIdPropName] !== null && itemObj[this._datasetIdPropName] !== undefined) {
437
- // get regular row item data
438
- originalDaraArray.push(this.readRegularRowData(columns, rowNumber, itemObj));
439
- } else if (this._hasGroupedItems && itemObj.__groupTotals === undefined) {
440
- // get the group row
441
- originalDaraArray.push([this.readGroupedRowTitle(itemObj)]);
442
- } else if (itemObj.__groupTotals) {
443
- // else if the row is a Group By and we have agreggators, then a property of '__groupTotals' would exist under that object
444
- originalDaraArray.push(this.readGroupedTotalRows(columns, itemObj));
445
- }
446
- }
447
- }
448
- return originalDaraArray;
449
- }
450
-
451
- /**
452
- * Get the data of a regular row (a row without grouping)
453
- * @param {Array<Object>} columns - column definitions
454
- * @param {Number} row - row index
455
- * @param {Object} itemObj - item datacontext object
456
- */
457
- protected readRegularRowData(columns: Column[], row: number, itemObj: any): string[] {
458
- let idx = 0;
459
- const rowOutputStrings = [];
460
- const columnsLn = columns.length;
461
- let prevColspan: number | string = 1;
462
- let colspanStartIndex = 0;
463
- const itemMetadata = this._dataView.getItemMetadata(row);
464
-
465
- for (let col = 0; col < columnsLn; col++) {
466
- const columnDef = columns[col];
467
-
468
- // skip excluded column
469
- if (columnDef.excludeFromExport) {
470
- continue;
471
- }
472
-
473
- // if we are grouping and are on 1st column index, we need to skip this column since it will be used later by the grouping text:: Group by [columnX]
474
- if (this._hasGroupedItems && idx === 0) {
475
- rowOutputStrings.push('');
476
- }
477
-
478
- let colspan = 1;
479
- let colspanColumnId;
480
- if (itemMetadata?.columns) {
481
- const metadata = itemMetadata.columns;
482
- const columnData = metadata[columnDef.id] || metadata[col];
483
- if (!((!isNaN(prevColspan as number) && +prevColspan > 1) || (prevColspan === '*' && col > 0))) {
484
- prevColspan = columnData?.colspan ?? 1;
485
- }
486
- if (prevColspan === '*') {
487
- colspan = columns.length - col;
488
- } else {
489
- colspan = prevColspan as number;
490
- if (columnDef.id in metadata) {
491
- colspanColumnId = columnDef.id;
492
- colspanStartIndex = col;
493
- }
494
- }
495
- }
496
-
497
- // when using grid with colspan, we will merge some cells together
498
- if ((prevColspan === '*' && col > 0) || ((!isNaN(prevColspan as number) && +prevColspan > 1) && columnDef.id !== colspanColumnId)) {
499
- // -- Merge Data
500
- // Excel row starts at 2 or at 3 when dealing with pre-header grouping
501
- const excelRowNumber = row + (this._hasColumnTitlePreHeader ? 3 : 2);
502
-
503
- if (typeof prevColspan === 'number' && (colspan - 1) === 1) {
504
- // partial column span
505
- const leftExcelColumnChar = this.getExcelColumnNameByIndex(colspanStartIndex + 1);
506
- const rightExcelColumnChar = this.getExcelColumnNameByIndex(col + 1);
507
- this._sheet.mergeCells(`${leftExcelColumnChar}${excelRowNumber}`, `${rightExcelColumnChar}${excelRowNumber}`);
508
- rowOutputStrings.push(''); // clear cell that won't be shown by a cell merge
509
- } else if (prevColspan === '*' && colspan === 1) {
510
- // full column span (from A1 until the last column)
511
- const rightExcelColumnChar = this.getExcelColumnNameByIndex(col + 1);
512
- this._sheet.mergeCells(`A${excelRowNumber}`, `${rightExcelColumnChar}${excelRowNumber}`);
513
- } else {
514
- rowOutputStrings.push(''); // clear cell that won't be shown by a cell merge
515
- }
516
-
517
- // decrement colspan until we reach colspan of 1 then proceed with cell merge OR full row merge when colspan is (*)
518
- if (typeof prevColspan === 'number' && (!isNaN(prevColspan as number) && +prevColspan > 1)) {
519
- colspan = prevColspan--;
520
- }
521
- } else {
522
- let itemData: Date | number | string | ExcelColumnMetadata = '';
523
- const fieldType = getColumnFieldType(columnDef);
524
-
525
- // -- Read Data & Push to Data Array
526
- // user might want to export with Formatter, and/or auto-detect Excel format, and/or export as regular cell data
527
-
528
- // for column that are Date type, we'll always export with their associated Date Formatters unless `exportWithFormatter` is specifically set to false
529
- const exportOptions = { ...this._excelExportOptions };
530
- if (columnDef.exportWithFormatter !== false && isColumnDateType(fieldType)) {
531
- exportOptions.exportWithFormatter = true;
532
- }
533
- itemData = exportWithFormatterWhenDefined(row, col, columnDef, itemObj, this._grid, exportOptions);
534
-
535
- // auto-detect best possible Excel format, unless the user provide his own formatting,
536
- // we only do this check once per column (everything after that will be pull from temp ref)
537
- if (!this._regularCellExcelFormats.hasOwnProperty(columnDef.id)) {
538
- const autoDetectCellFormat = columnDef.excelExportOptions?.autoDetectCellFormat ?? this._excelExportOptions?.autoDetectCellFormat;
539
- const cellStyleFormat = useCellFormatByFieldType(this._stylesheet, this._stylesheetFormats, columnDef, this._grid, autoDetectCellFormat);
540
- // user could also override style and/or valueParserCallback
541
- if (columnDef.excelExportOptions?.style) {
542
- cellStyleFormat.stylesheetFormatterId = this._stylesheet.createFormat(columnDef.excelExportOptions.style).id;
543
- }
544
- if (columnDef.excelExportOptions?.valueParserCallback) {
545
- cellStyleFormat.getDataValueParser = columnDef.excelExportOptions.valueParserCallback;
546
- }
547
- this._regularCellExcelFormats[columnDef.id] = cellStyleFormat;
548
- }
549
-
550
- // sanitize early, when enabled, any HTML tags (remove HTML tags)
551
- if (typeof itemData === 'string' && (columnDef.sanitizeDataExport || this._excelExportOptions.sanitizeDataExport)) {
552
- itemData = stripTags(itemData as string);
553
- }
554
-
555
- const { stylesheetFormatterId, getDataValueParser } = this._regularCellExcelFormats[columnDef.id];
556
- itemData = getDataValueParser(itemData, columnDef, stylesheetFormatterId, this._stylesheet, this._gridOptions);
557
-
558
- rowOutputStrings.push(itemData);
559
- idx++;
560
- }
561
- }
562
-
563
- return rowOutputStrings as string[];
564
- }
565
-
566
- /**
567
- * Get the grouped title(s) and its group title formatter, for example if we grouped by salesRep, the returned result would be:: 'Sales Rep: John Dow (2 items)'
568
- * @param itemObj
569
- */
570
- protected readGroupedRowTitle(itemObj: any): string {
571
- const groupName = stripTags(itemObj.title);
572
-
573
- if (this._excelExportOptions && this._excelExportOptions.addGroupIndentation) {
574
- const collapsedSymbol = this._excelExportOptions && this._excelExportOptions.groupCollapsedSymbol || '⮞';
575
- const expandedSymbol = this._excelExportOptions && this._excelExportOptions.groupExpandedSymbol || '⮟';
576
- const chevron = itemObj.collapsed ? collapsedSymbol : expandedSymbol;
577
- return chevron + ' ' + addWhiteSpaces(5 * itemObj.level) + groupName;
578
- }
579
- return groupName;
580
- }
581
-
582
- /**
583
- * Get the grouped totals (below the regular rows), these are set by Slick Aggregators.
584
- * For example if we grouped by "salesRep" and we have a Sum Aggregator on "sales", then the returned output would be:: ["Sum 123$"]
585
- * @param itemObj
586
- */
587
- protected readGroupedTotalRows(columns: Column[], itemObj: any): Array<ExcelColumnMetadata | string | number> {
588
- const groupingAggregatorRowText = this._excelExportOptions.groupingAggregatorRowText || '';
589
- const outputStrings: Array<ExcelColumnMetadata | string | number> = [groupingAggregatorRowText];
590
-
591
- columns.forEach((columnDef) => {
592
- let itemData: number | string | ExcelColumnMetadata = '';
593
- const fieldType = getColumnFieldType(columnDef);
594
- const skippedField = columnDef.excludeFromExport || false;
595
-
596
- // if there's a exportCustomGroupTotalsFormatter or groupTotalsFormatter, we will re-run it to get the exact same output as what is shown in UI
597
- if (columnDef.exportCustomGroupTotalsFormatter) {
598
- const totalResult = columnDef.exportCustomGroupTotalsFormatter(itemObj, columnDef, this._grid);
599
- itemData = totalResult instanceof HTMLElement ? totalResult.textContent || '' : totalResult;
600
- }
601
-
602
- // auto-detect best possible Excel format for Group Totals, unless the user provide his own formatting,
603
- // we only do this check once per column (everything after that will be pull from temp ref)
604
- const autoDetectCellFormat = columnDef.excelExportOptions?.autoDetectCellFormat ?? this._excelExportOptions?.autoDetectCellFormat;
605
- if (fieldType === FieldType.number && autoDetectCellFormat !== false) {
606
- let groupCellFormat = this._groupTotalExcelFormats[columnDef.id];
607
- if (!groupCellFormat?.groupType) {
608
- groupCellFormat = getExcelFormatFromGridFormatter(this._stylesheet, this._stylesheetFormats, columnDef, this._grid, 'group');
609
- if (columnDef.groupTotalsExcelExportOptions?.style) {
610
- groupCellFormat.stylesheetFormatter = this._stylesheet.createFormat(columnDef.groupTotalsExcelExportOptions.style);
611
- }
612
- this._groupTotalExcelFormats[columnDef.id] = groupCellFormat;
613
- }
614
-
615
- const groupTotalParser = columnDef.groupTotalsExcelExportOptions?.valueParserCallback ?? getGroupTotalValue;
616
- if (itemObj[groupCellFormat.groupType]?.[columnDef.field] !== undefined) {
617
- itemData = {
618
- value: groupTotalParser(itemObj, columnDef, groupCellFormat.groupType, this._stylesheet),
619
- metadata: { style: groupCellFormat.stylesheetFormatter?.id }
620
- };
621
- }
622
- } else if (columnDef.groupTotalsFormatter) {
623
- const totalResult = columnDef.groupTotalsFormatter(itemObj, columnDef, this._grid);
624
- itemData = totalResult instanceof HTMLElement ? totalResult.textContent || '' : totalResult;
625
- }
626
-
627
- // does the user want to sanitize the output data (remove HTML tags)?
628
- if (typeof itemData === 'string' && (columnDef.sanitizeDataExport || this._excelExportOptions.sanitizeDataExport)) {
629
- itemData = stripTags(itemData);
630
- }
631
-
632
- // add the column (unless user wants to skip it)
633
- if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
634
- outputStrings.push(itemData);
635
- }
636
- });
637
-
638
- return outputStrings;
639
- }
640
- }
1
+ import {
2
+ downloadExcelFile,
3
+ type ExcelColumnMetadata,
4
+ type ExcelMetadata,
5
+ type StyleSheet,
6
+ Workbook,
7
+ type Worksheet,
8
+ } from 'excel-builder-vanilla';
9
+ import type {
10
+ Column,
11
+ ContainerService,
12
+ ExcelExportService as BaseExcelExportService,
13
+ ExcelExportOption,
14
+ ExternalResource,
15
+
16
+ GetDataValueCallback,
17
+ GetGroupTotalValueCallback,
18
+ GridOption,
19
+ KeyTitlePair,
20
+ Locale,
21
+ PubSubService,
22
+ SlickDataView,
23
+ SlickGrid,
24
+ TranslaterService,
25
+ } from '@slickgrid-universal/common';
26
+ import {
27
+ Constants,
28
+ // utility functions
29
+ exportWithFormatterWhenDefined,
30
+ FieldType,
31
+ FileType,
32
+ getColumnFieldType,
33
+ getTranslationPrefix,
34
+ isColumnDateType,
35
+ } from '@slickgrid-universal/common';
36
+ import { addWhiteSpaces, extend, getHtmlStringOutput, stripTags, titleCase } from '@slickgrid-universal/utils';
37
+
38
+ import {
39
+ type ExcelFormatter,
40
+ getGroupTotalValue,
41
+ getExcelFormatFromGridFormatter,
42
+ useCellFormatByFieldType,
43
+ } from './excelUtils';
44
+
45
+ const DEFAULT_EXPORT_OPTIONS: ExcelExportOption = {
46
+ filename: 'export',
47
+ format: FileType.xlsx
48
+ };
49
+
50
+ export class ExcelExportService implements ExternalResource, BaseExcelExportService {
51
+ protected _fileFormat = FileType.xlsx;
52
+ protected _grid!: SlickGrid;
53
+ protected _locales!: Locale;
54
+ protected _groupedColumnHeaders?: Array<KeyTitlePair>;
55
+ protected _columnHeaders: Array<KeyTitlePair> = [];
56
+ protected _hasColumnTitlePreHeader = false;
57
+ protected _hasGroupedItems = false;
58
+ protected _excelExportOptions!: ExcelExportOption;
59
+ protected _sheet!: Worksheet;
60
+ protected _stylesheet!: StyleSheet;
61
+ protected _stylesheetFormats: any;
62
+ protected _pubSubService: PubSubService | null = null;
63
+ protected _translaterService: TranslaterService | undefined;
64
+ protected _workbook!: Workbook;
65
+
66
+ // references of each detected cell and/or group total formats
67
+ protected _regularCellExcelFormats: { [fieldId: string]: { stylesheetFormatterId?: number; getDataValueParser: GetDataValueCallback; }; } = {};
68
+ protected _groupTotalExcelFormats: { [fieldId: string]: { groupType: string; stylesheetFormatter?: ExcelFormatter; getGroupTotalParser?: GetGroupTotalValueCallback; }; } = {};
69
+
70
+ /** ExcelExportService class name which is use to find service instance in the external registered services */
71
+ readonly className = 'ExcelExportService';
72
+
73
+ protected get _datasetIdPropName(): string {
74
+ return this._gridOptions?.datasetIdPropertyName ?? 'id';
75
+ }
76
+
77
+ /** Getter of SlickGrid DataView object */
78
+ get _dataView(): SlickDataView {
79
+ return this._grid?.getData<SlickDataView>();
80
+ }
81
+
82
+ /** Getter for the Grid Options pulled through the Grid Object */
83
+ protected get _gridOptions(): GridOption {
84
+ return this._grid?.getOptions() || {} as GridOption;
85
+ }
86
+
87
+ get stylesheet() {
88
+ return this._stylesheet;
89
+ }
90
+
91
+ get stylesheetFormats() {
92
+ return this._stylesheetFormats;
93
+ }
94
+
95
+ get groupTotalExcelFormats() {
96
+ return this._groupTotalExcelFormats;
97
+ }
98
+
99
+ get regularCellExcelFormats() {
100
+ return this._regularCellExcelFormats;
101
+ }
102
+
103
+ dispose() {
104
+ this._pubSubService?.unsubscribeAll();
105
+ }
106
+
107
+ /**
108
+ * Initialize the Export Service
109
+ * @param grid
110
+ * @param containerService
111
+ */
112
+ init(grid: SlickGrid, containerService: ContainerService): void {
113
+ this._grid = grid;
114
+ this._pubSubService = containerService.get<PubSubService>('PubSubService');
115
+
116
+ // get locales provided by user in main file or else use default English locales via the Constants
117
+ this._locales = this._gridOptions?.locales ?? Constants.locales;
118
+ this._translaterService = this._gridOptions?.translater;
119
+
120
+ if (this._gridOptions.enableTranslate && (!this._translaterService || !this._translaterService.translate)) {
121
+ throw new Error('[Slickgrid-Universal] requires a Translate Service to be passed in the "translater" Grid Options when "enableTranslate" is enabled. (example: this.gridOptions = { enableTranslate: true, translater: this.translaterService })');
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Function to export the Grid result to an Excel CSV format using javascript for it to produce the CSV file.
127
+ * This is a WYSIWYG export to file output (What You See is What You Get)
128
+ *
129
+ * NOTES: The column position needs to match perfectly the JSON Object position because of the way we are pulling the data,
130
+ * which means that if any column(s) got moved in the UI, it has to be reflected in the JSON array output as well
131
+ *
132
+ * Example: exportToExcel({ format: FileType.csv, delimiter: DelimiterType.comma })
133
+ */
134
+ exportToExcel(options?: ExcelExportOption): Promise<boolean> {
135
+ if (!this._grid || !this._dataView || !this._pubSubService) {
136
+ throw new Error('[Slickgrid-Universal] it seems that the SlickGrid & DataView objects and/or PubSubService are not initialized did you forget to enable the grid option flag "enableExcelExport"?');
137
+ }
138
+ this._pubSubService?.publish(`onBeforeExportToExcel`, true);
139
+ this._excelExportOptions = extend(true, {}, { ...DEFAULT_EXPORT_OPTIONS, ...this._gridOptions.excelExportOptions, ...options });
140
+ this._fileFormat = this._excelExportOptions.format || FileType.xlsx;
141
+
142
+ // reset references of detected Excel formats
143
+ this._regularCellExcelFormats = {};
144
+ this._groupTotalExcelFormats = {};
145
+
146
+ // wrap in a Promise so that we can add loading spinner
147
+ return new Promise(resolve => {
148
+ // prepare the Excel Workbook & Sheet
149
+ // we can use ExcelBuilder constructor with WebPack but we need to use function calls with RequireJS/SystemJS
150
+ const worksheetOptions = { name: this._excelExportOptions.sheetName || 'Sheet1' };
151
+ this._workbook = new Workbook();
152
+ this._sheet = this._workbook.createWorksheet(worksheetOptions);
153
+
154
+ // add any Excel Format/Stylesheet to current Workbook
155
+ this._stylesheet = this._workbook.getStyleSheet();
156
+
157
+ // create some common default Excel formatters that will be used
158
+ const boldFormatter = this._stylesheet.createFormat({ font: { bold: true } });
159
+ const stringFormatter = this._stylesheet.createFormat({ format: '@' });
160
+ const numberFormatter = this._stylesheet.createFormat({ format: '0' });
161
+ this._stylesheetFormats = {
162
+ boldFormatter,
163
+ numberFormatter,
164
+ stringFormatter,
165
+ };
166
+ this._sheet.setColumnFormats([boldFormatter]);
167
+
168
+ // get the CSV output from the grid data
169
+ const dataOutput = this.getDataOutput();
170
+
171
+ // trigger a download file
172
+ // wrap it into a setTimeout so that the EventAggregator has enough time to start a pre-process like showing a spinner
173
+ setTimeout(async () => {
174
+ if (this._gridOptions?.excelExportOptions?.customExcelHeader) {
175
+ this._gridOptions.excelExportOptions.customExcelHeader(this._workbook, this._sheet);
176
+ }
177
+
178
+ const columns = this._grid?.getColumns() || [];
179
+ this._sheet.setColumns(this.getColumnStyles(columns));
180
+
181
+ const currentSheetData = this._sheet.data;
182
+ let finalOutput = currentSheetData;
183
+ if (Array.isArray(currentSheetData) && Array.isArray(dataOutput)) {
184
+ finalOutput = this._sheet.data.concat(dataOutput);
185
+ }
186
+
187
+ this._sheet.setData(finalOutput);
188
+ this._workbook.addWorksheet(this._sheet);
189
+
190
+ // MIME type could be undefined, if that's the case we'll detect the type by its file extension
191
+ // user could also provide its own mime type, if however an empty string is provided we will consider to be without any MIME type)
192
+ let mimeType = this._excelExportOptions?.mimeType;
193
+ if (mimeType === undefined) {
194
+ mimeType = this._fileFormat === FileType.xls ? 'application/vnd.ms-excel' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
195
+ }
196
+
197
+ const filename = `${this._excelExportOptions.filename}.${this._fileFormat}`;
198
+ downloadExcelFile(this._workbook, filename, { mimeType }).then(() => {
199
+ this._pubSubService?.publish(`onAfterExportToExcel`, { filename, mimeType });
200
+ resolve(true);
201
+ });
202
+ });
203
+ });
204
+ }
205
+
206
+ /**
207
+ * Takes a positive integer and returns the corresponding column name.
208
+ * dealing with the Excel column position is a bit tricky since the first 26 columns are single char (A,B,...) but after that it becomes double char (AA,AB,...)
209
+ * so we must first see if we are in the first section of 26 chars, if that is the case we just concatenate 1 (1st row) so it becomes (A1, B1, ...)
210
+ * and again if we go 26, we need to add yet again an extra prefix (AA1, AB1, ...) and so goes the cycle
211
+ * @param {number} colIndex - The positive integer to convert to a column name.
212
+ * @return {string} The column name.
213
+ */
214
+ getExcelColumnNameByIndex(colIndex: number): string {
215
+ const letters = 'ZABCDEFGHIJKLMNOPQRSTUVWXY';
216
+
217
+ let nextPos = Math.floor(colIndex / 26);
218
+ const lastPos = Math.floor(colIndex % 26);
219
+ if (lastPos === 0) {
220
+ nextPos--;
221
+ }
222
+
223
+ if (colIndex > 26) {
224
+ return this.getExcelColumnNameByIndex(nextPos) + letters[lastPos];
225
+ }
226
+
227
+ return letters[lastPos] + '';
228
+ }
229
+
230
+ // -----------------------
231
+ // protected functions
232
+ // -----------------------
233
+
234
+ protected getDataOutput(): Array<string[] | ExcelColumnMetadata[]> {
235
+ const columns = this._grid?.getColumns() || [];
236
+
237
+ // data variable which will hold all the fields data of a row
238
+ const outputData: Array<string[] | ExcelColumnMetadata[]> = [];
239
+ const gridExportOptions = this._gridOptions?.excelExportOptions;
240
+ const columnHeaderStyle = gridExportOptions?.columnHeaderStyle;
241
+ let columnHeaderStyleId = this._stylesheetFormats.boldFormatter.id;
242
+ if (columnHeaderStyle) {
243
+ columnHeaderStyleId = this._stylesheet.createFormat(columnHeaderStyle).id;
244
+ }
245
+
246
+ // get all Grouped Column Header Titles when defined (from pre-header row)
247
+ if (this._gridOptions.createPreHeaderPanel && this._gridOptions.showPreHeaderPanel && !this._gridOptions.enableDraggableGrouping) {
248
+ // when having Grouped Header Titles (in the pre-header), then make the cell Bold & Aligned Center
249
+ const boldCenterAlign = this._stylesheet.createFormat({ alignment: { horizontal: 'center' }, font: { bold: true } });
250
+ outputData.push(this.getColumnGroupedHeaderTitlesData(columns, { style: boldCenterAlign?.id }));
251
+ this._hasColumnTitlePreHeader = true;
252
+ }
253
+
254
+ // get all Column Header Titles (it might include a "Group by" title at A1 cell)
255
+ // also style the headers, defaults to Bold but user could pass his own style
256
+ outputData.push(this.getColumnHeaderData(columns, { style: columnHeaderStyleId }));
257
+
258
+ // Populate the rest of the Grid Data
259
+ this.pushAllGridRowDataToArray(outputData, columns);
260
+
261
+ return outputData;
262
+ }
263
+
264
+ /** Get each column style including a style for the width of each column */
265
+ protected getColumnStyles(columns: Column[]): any[] {
266
+ const grouping = this._dataView.getGrouping();
267
+ const columnStyles = [];
268
+ if (Array.isArray(grouping) && grouping.length > 0) {
269
+ columnStyles.push({
270
+ bestFit: true,
271
+ columnStyles: this._gridOptions?.excelExportOptions?.customColumnWidth ?? 10
272
+ });
273
+ }
274
+
275
+ columns.forEach((columnDef: Column) => {
276
+ const skippedField = columnDef.excludeFromExport ?? false;
277
+ // if column width is 0, then we consider that field as a hidden field and should not be part of the export
278
+ if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
279
+ columnStyles.push({
280
+ bestFit: true,
281
+ width: columnDef.excelExportOptions?.width ?? this._gridOptions?.excelExportOptions?.customColumnWidth ?? 10
282
+ });
283
+ }
284
+ });
285
+ return columnStyles;
286
+ }
287
+
288
+ /**
289
+ * Get all Grouped Header Titles and their keys, translate the title when required, and format them in Bold
290
+ * @param {Array<Object>} columns - grid column definitions
291
+ * @param {Object} metadata - Excel metadata
292
+ * @returns {Object} array of Excel cell format
293
+ */
294
+ protected getColumnGroupedHeaderTitlesData(columns: Column[], metadata: ExcelMetadata): Array<ExcelColumnMetadata> {
295
+ let outputGroupedHeaderTitles: Array<ExcelColumnMetadata> = [];
296
+
297
+ // get all Column Header Titles
298
+ this._groupedColumnHeaders = this.getColumnGroupedHeaderTitles(columns) || [];
299
+ if (this._groupedColumnHeaders && Array.isArray(this._groupedColumnHeaders) && this._groupedColumnHeaders.length > 0) {
300
+ // add the header row + add a new line at the end of the row
301
+ outputGroupedHeaderTitles = this._groupedColumnHeaders.map((header) => ({ value: header.title, metadata }));
302
+ }
303
+
304
+ // merge necessary cells (any grouped header titles)
305
+ let colspanStartIndex = 0;
306
+ const headersLn = this._groupedColumnHeaders.length;
307
+ for (let cellIndex = 0; cellIndex < headersLn; cellIndex++) {
308
+ if ((cellIndex + 1) === headersLn || ((cellIndex + 1) < headersLn && this._groupedColumnHeaders[cellIndex].title !== this._groupedColumnHeaders[cellIndex + 1].title)) {
309
+ const leftExcelColumnChar = this.getExcelColumnNameByIndex(colspanStartIndex + 1);
310
+ const rightExcelColumnChar = this.getExcelColumnNameByIndex(cellIndex + 1);
311
+ this._sheet.mergeCells(`${leftExcelColumnChar}1`, `${rightExcelColumnChar}1`);
312
+
313
+ // next group starts 1 column index away
314
+ colspanStartIndex = cellIndex + 1;
315
+ }
316
+ }
317
+
318
+ return outputGroupedHeaderTitles;
319
+ }
320
+
321
+ /** Get all column headers and format them in Bold */
322
+ protected getColumnHeaderData(columns: Column[], metadata: ExcelMetadata): Array<ExcelColumnMetadata> {
323
+ let outputHeaderTitles: Array<ExcelColumnMetadata> = [];
324
+
325
+ // get all Column Header Titles
326
+ this._columnHeaders = this.getColumnHeaders(columns) || [];
327
+ if (this._columnHeaders && Array.isArray(this._columnHeaders) && this._columnHeaders.length > 0) {
328
+ // add the header row + add a new line at the end of the row
329
+ outputHeaderTitles = this._columnHeaders.map((header) => ({ value: stripTags(header.title), metadata }));
330
+ }
331
+
332
+ // do we have a Group by title?
333
+ const groupTitle = this.getGroupColumnTitle();
334
+ if (groupTitle) {
335
+ outputHeaderTitles.unshift({ value: groupTitle, metadata });
336
+ }
337
+
338
+ return outputHeaderTitles;
339
+ }
340
+
341
+ protected getGroupColumnTitle(): string | null {
342
+ // Group By text, it could be set in the export options or from translation or if nothing is found then use the English constant text
343
+ let groupByColumnHeader = this._excelExportOptions.groupingColumnHeaderTitle;
344
+ if (!groupByColumnHeader && this._gridOptions.enableTranslate && this._translaterService?.translate) {
345
+ groupByColumnHeader = this._translaterService.translate(`${getTranslationPrefix(this._gridOptions)}GROUP_BY`);
346
+ } else if (!groupByColumnHeader) {
347
+ groupByColumnHeader = this._locales && this._locales.TEXT_GROUP_BY;
348
+ }
349
+
350
+ // get grouped column titles and if found, we will add a "Group by" column at the first column index
351
+ // if it's a CSV format, we'll escape the text in double quotes
352
+ const grouping = this._dataView.getGrouping();
353
+ if (Array.isArray(grouping) && grouping.length > 0) {
354
+ this._hasGroupedItems = true;
355
+ return groupByColumnHeader;
356
+ } else {
357
+ this._hasGroupedItems = false;
358
+ }
359
+ return null;
360
+ }
361
+
362
+ /**
363
+ * Get all Grouped Header Titles and their keys, translate the title when required.
364
+ * @param {Array<object>} columns of the grid
365
+ */
366
+ protected getColumnGroupedHeaderTitles(columns: Column[]): Array<KeyTitlePair> {
367
+ const groupedColumnHeaders: Array<KeyTitlePair> = [];
368
+
369
+ if (columns && Array.isArray(columns)) {
370
+ // Populate the Grouped Column Header, pull the columnGroup(Key) defined
371
+ columns.forEach((columnDef) => {
372
+ let groupedHeaderTitle = '';
373
+ if (columnDef.columnGroupKey && this._gridOptions.enableTranslate && this._translaterService?.translate) {
374
+ groupedHeaderTitle = this._translaterService.translate(columnDef.columnGroupKey);
375
+ } else {
376
+ groupedHeaderTitle = columnDef.columnGroup || '';
377
+ }
378
+ const skippedField = columnDef.excludeFromExport || false;
379
+
380
+ // if column width is 0px, then we consider that field as a hidden field and should not be part of the export
381
+ if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
382
+ groupedColumnHeaders.push({
383
+ key: (columnDef.field || columnDef.id) as string,
384
+ title: groupedHeaderTitle || ''
385
+ });
386
+ }
387
+ });
388
+ }
389
+ return groupedColumnHeaders;
390
+ }
391
+
392
+ /**
393
+ * Get all header titles and their keys, translate the title when required.
394
+ * @param {Array<object>} columns of the grid
395
+ */
396
+ protected getColumnHeaders(columns: Column[]): Array<KeyTitlePair> | null {
397
+ const columnHeaders: Array<KeyTitlePair> = [];
398
+
399
+ if (columns && Array.isArray(columns)) {
400
+ // Populate the Column Header, pull the name defined
401
+ columns.forEach((columnDef) => {
402
+ let headerTitle = '';
403
+ if ((columnDef.nameKey || columnDef.nameKey) && this._gridOptions.enableTranslate && this._translaterService?.translate) {
404
+ headerTitle = this._translaterService.translate((columnDef.nameKey || columnDef.nameKey));
405
+ } else {
406
+ headerTitle = getHtmlStringOutput(columnDef.name || '', 'innerHTML') || titleCase(columnDef.field);
407
+ }
408
+ const skippedField = columnDef.excludeFromExport || false;
409
+
410
+ // if column width is 0, then we consider that field as a hidden field and should not be part of the export
411
+ if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
412
+ columnHeaders.push({
413
+ key: (columnDef.field || columnDef.id) + '',
414
+ title: headerTitle
415
+ });
416
+ }
417
+ });
418
+ }
419
+ return columnHeaders;
420
+ }
421
+
422
+ /**
423
+ * Get all the grid row data and return that as an output string
424
+ */
425
+ protected pushAllGridRowDataToArray(originalDaraArray: Array<Array<string | ExcelColumnMetadata | number>>, columns: Column[]): Array<Array<string | ExcelColumnMetadata | number>> {
426
+ const lineCount = this._dataView.getLength();
427
+
428
+ // loop through all the grid rows of data
429
+ for (let rowNumber = 0; rowNumber < lineCount; rowNumber++) {
430
+ const itemObj = this._dataView.getItem(rowNumber);
431
+
432
+ // make sure we have a filled object AND that the item doesn't include the "getItem" method
433
+ // this happen could happen with an opened Row Detail as it seems to include an empty Slick DataView (we'll just skip those lines)
434
+ if (itemObj && !itemObj.hasOwnProperty('getItem')) {
435
+ // Normal row (not grouped by anything) would have an ID which was predefined in the Grid Columns definition
436
+ if (itemObj[this._datasetIdPropName] !== null && itemObj[this._datasetIdPropName] !== undefined) {
437
+ // get regular row item data
438
+ originalDaraArray.push(this.readRegularRowData(columns, rowNumber, itemObj));
439
+ } else if (this._hasGroupedItems && itemObj.__groupTotals === undefined) {
440
+ // get the group row
441
+ originalDaraArray.push([this.readGroupedRowTitle(itemObj)]);
442
+ } else if (itemObj.__groupTotals) {
443
+ // else if the row is a Group By and we have agreggators, then a property of '__groupTotals' would exist under that object
444
+ originalDaraArray.push(this.readGroupedTotalRows(columns, itemObj));
445
+ }
446
+ }
447
+ }
448
+ return originalDaraArray;
449
+ }
450
+
451
+ /**
452
+ * Get the data of a regular row (a row without grouping)
453
+ * @param {Array<Object>} columns - column definitions
454
+ * @param {Number} row - row index
455
+ * @param {Object} itemObj - item datacontext object
456
+ */
457
+ protected readRegularRowData(columns: Column[], row: number, itemObj: any): string[] {
458
+ let idx = 0;
459
+ const rowOutputStrings = [];
460
+ const columnsLn = columns.length;
461
+ let prevColspan: number | string = 1;
462
+ let colspanStartIndex = 0;
463
+ const itemMetadata = this._dataView.getItemMetadata(row);
464
+
465
+ for (let col = 0; col < columnsLn; col++) {
466
+ const columnDef = columns[col];
467
+
468
+ // skip excluded column
469
+ if (columnDef.excludeFromExport) {
470
+ continue;
471
+ }
472
+
473
+ // if we are grouping and are on 1st column index, we need to skip this column since it will be used later by the grouping text:: Group by [columnX]
474
+ if (this._hasGroupedItems && idx === 0) {
475
+ rowOutputStrings.push('');
476
+ }
477
+
478
+ let colspan = 1;
479
+ let colspanColumnId;
480
+ if (itemMetadata?.columns) {
481
+ const metadata = itemMetadata.columns;
482
+ const columnData = metadata[columnDef.id] || metadata[col];
483
+ if (!((!isNaN(prevColspan as number) && +prevColspan > 1) || (prevColspan === '*' && col > 0))) {
484
+ prevColspan = columnData?.colspan ?? 1;
485
+ }
486
+ if (prevColspan === '*') {
487
+ colspan = columns.length - col;
488
+ } else {
489
+ colspan = prevColspan as number;
490
+ if (columnDef.id in metadata) {
491
+ colspanColumnId = columnDef.id;
492
+ colspanStartIndex = col;
493
+ }
494
+ }
495
+ }
496
+
497
+ // when using grid with colspan, we will merge some cells together
498
+ if ((prevColspan === '*' && col > 0) || ((!isNaN(prevColspan as number) && +prevColspan > 1) && columnDef.id !== colspanColumnId)) {
499
+ // -- Merge Data
500
+ // Excel row starts at 2 or at 3 when dealing with pre-header grouping
501
+ const excelRowNumber = row + (this._hasColumnTitlePreHeader ? 3 : 2);
502
+
503
+ if (typeof prevColspan === 'number' && (colspan - 1) === 1) {
504
+ // partial column span
505
+ const leftExcelColumnChar = this.getExcelColumnNameByIndex(colspanStartIndex + 1);
506
+ const rightExcelColumnChar = this.getExcelColumnNameByIndex(col + 1);
507
+ this._sheet.mergeCells(`${leftExcelColumnChar}${excelRowNumber}`, `${rightExcelColumnChar}${excelRowNumber}`);
508
+ rowOutputStrings.push(''); // clear cell that won't be shown by a cell merge
509
+ } else if (prevColspan === '*' && colspan === 1) {
510
+ // full column span (from A1 until the last column)
511
+ const rightExcelColumnChar = this.getExcelColumnNameByIndex(col + 1);
512
+ this._sheet.mergeCells(`A${excelRowNumber}`, `${rightExcelColumnChar}${excelRowNumber}`);
513
+ } else {
514
+ rowOutputStrings.push(''); // clear cell that won't be shown by a cell merge
515
+ }
516
+
517
+ // decrement colspan until we reach colspan of 1 then proceed with cell merge OR full row merge when colspan is (*)
518
+ if (typeof prevColspan === 'number' && (!isNaN(prevColspan as number) && +prevColspan > 1)) {
519
+ colspan = prevColspan--;
520
+ }
521
+ } else {
522
+ let itemData: Date | number | string | ExcelColumnMetadata = '';
523
+ const fieldType = getColumnFieldType(columnDef);
524
+
525
+ // -- Read Data & Push to Data Array
526
+ // user might want to export with Formatter, and/or auto-detect Excel format, and/or export as regular cell data
527
+
528
+ // for column that are Date type, we'll always export with their associated Date Formatters unless `exportWithFormatter` is specifically set to false
529
+ const exportOptions = { ...this._excelExportOptions };
530
+ if (columnDef.exportWithFormatter !== false && isColumnDateType(fieldType)) {
531
+ exportOptions.exportWithFormatter = true;
532
+ }
533
+ itemData = exportWithFormatterWhenDefined(row, col, columnDef, itemObj, this._grid, exportOptions);
534
+
535
+ // auto-detect best possible Excel format, unless the user provide his own formatting,
536
+ // we only do this check once per column (everything after that will be pull from temp ref)
537
+ if (!this._regularCellExcelFormats.hasOwnProperty(columnDef.id)) {
538
+ const autoDetectCellFormat = columnDef.excelExportOptions?.autoDetectCellFormat ?? this._excelExportOptions?.autoDetectCellFormat;
539
+ const cellStyleFormat = useCellFormatByFieldType(this._stylesheet, this._stylesheetFormats, columnDef, this._grid, autoDetectCellFormat);
540
+ // user could also override style and/or valueParserCallback
541
+ if (columnDef.excelExportOptions?.style) {
542
+ cellStyleFormat.stylesheetFormatterId = this._stylesheet.createFormat(columnDef.excelExportOptions.style).id;
543
+ }
544
+ if (columnDef.excelExportOptions?.valueParserCallback) {
545
+ cellStyleFormat.getDataValueParser = columnDef.excelExportOptions.valueParserCallback;
546
+ }
547
+ this._regularCellExcelFormats[columnDef.id] = cellStyleFormat;
548
+ }
549
+
550
+ // sanitize early, when enabled, any HTML tags (remove HTML tags)
551
+ if (typeof itemData === 'string' && (columnDef.sanitizeDataExport || this._excelExportOptions.sanitizeDataExport)) {
552
+ itemData = stripTags(itemData as string);
553
+ }
554
+
555
+ const { stylesheetFormatterId, getDataValueParser } = this._regularCellExcelFormats[columnDef.id];
556
+ itemData = getDataValueParser(itemData, columnDef, stylesheetFormatterId, this._stylesheet, this._gridOptions);
557
+
558
+ rowOutputStrings.push(itemData);
559
+ idx++;
560
+ }
561
+ }
562
+
563
+ return rowOutputStrings as string[];
564
+ }
565
+
566
+ /**
567
+ * Get the grouped title(s) and its group title formatter, for example if we grouped by salesRep, the returned result would be:: 'Sales Rep: John Dow (2 items)'
568
+ * @param itemObj
569
+ */
570
+ protected readGroupedRowTitle(itemObj: any): string {
571
+ const groupName = stripTags(itemObj.title);
572
+
573
+ if (this._excelExportOptions && this._excelExportOptions.addGroupIndentation) {
574
+ const collapsedSymbol = this._excelExportOptions && this._excelExportOptions.groupCollapsedSymbol || '⮞';
575
+ const expandedSymbol = this._excelExportOptions && this._excelExportOptions.groupExpandedSymbol || '⮟';
576
+ const chevron = itemObj.collapsed ? collapsedSymbol : expandedSymbol;
577
+ return chevron + ' ' + addWhiteSpaces(5 * itemObj.level) + groupName;
578
+ }
579
+ return groupName;
580
+ }
581
+
582
+ /**
583
+ * Get the grouped totals (below the regular rows), these are set by Slick Aggregators.
584
+ * For example if we grouped by "salesRep" and we have a Sum Aggregator on "sales", then the returned output would be:: ["Sum 123$"]
585
+ * @param itemObj
586
+ */
587
+ protected readGroupedTotalRows(columns: Column[], itemObj: any): Array<ExcelColumnMetadata | string | number> {
588
+ const groupingAggregatorRowText = this._excelExportOptions.groupingAggregatorRowText || '';
589
+ const outputStrings: Array<ExcelColumnMetadata | string | number> = [groupingAggregatorRowText];
590
+
591
+ columns.forEach((columnDef) => {
592
+ let itemData: number | string | ExcelColumnMetadata = '';
593
+ const fieldType = getColumnFieldType(columnDef);
594
+ const skippedField = columnDef.excludeFromExport || false;
595
+
596
+ // if there's a exportCustomGroupTotalsFormatter or groupTotalsFormatter, we will re-run it to get the exact same output as what is shown in UI
597
+ if (columnDef.exportCustomGroupTotalsFormatter) {
598
+ const totalResult = columnDef.exportCustomGroupTotalsFormatter(itemObj, columnDef, this._grid);
599
+ itemData = totalResult instanceof HTMLElement ? totalResult.textContent || '' : totalResult;
600
+ }
601
+
602
+ // auto-detect best possible Excel format for Group Totals, unless the user provide his own formatting,
603
+ // we only do this check once per column (everything after that will be pull from temp ref)
604
+ const autoDetectCellFormat = columnDef.excelExportOptions?.autoDetectCellFormat ?? this._excelExportOptions?.autoDetectCellFormat;
605
+ if (fieldType === FieldType.number && autoDetectCellFormat !== false) {
606
+ let groupCellFormat = this._groupTotalExcelFormats[columnDef.id];
607
+ if (!groupCellFormat?.groupType) {
608
+ groupCellFormat = getExcelFormatFromGridFormatter(this._stylesheet, this._stylesheetFormats, columnDef, this._grid, 'group');
609
+ if (columnDef.groupTotalsExcelExportOptions?.style) {
610
+ groupCellFormat.stylesheetFormatter = this._stylesheet.createFormat(columnDef.groupTotalsExcelExportOptions.style);
611
+ }
612
+ this._groupTotalExcelFormats[columnDef.id] = groupCellFormat;
613
+ }
614
+
615
+ const groupTotalParser = columnDef.groupTotalsExcelExportOptions?.valueParserCallback ?? getGroupTotalValue;
616
+ if (itemObj[groupCellFormat.groupType]?.[columnDef.field] !== undefined) {
617
+ itemData = {
618
+ value: groupTotalParser(itemObj, columnDef, groupCellFormat.groupType, this._stylesheet),
619
+ metadata: { style: groupCellFormat.stylesheetFormatter?.id }
620
+ };
621
+ }
622
+ } else if (columnDef.groupTotalsFormatter) {
623
+ const totalResult = columnDef.groupTotalsFormatter(itemObj, columnDef, this._grid);
624
+ itemData = totalResult instanceof HTMLElement ? totalResult.textContent || '' : totalResult;
625
+ }
626
+
627
+ // does the user want to sanitize the output data (remove HTML tags)?
628
+ if (typeof itemData === 'string' && (columnDef.sanitizeDataExport || this._excelExportOptions.sanitizeDataExport)) {
629
+ itemData = stripTags(itemData);
630
+ }
631
+
632
+ // add the column (unless user wants to skip it)
633
+ if ((columnDef.width === undefined || columnDef.width > 0) && !skippedField) {
634
+ outputStrings.push(itemData);
635
+ }
636
+ });
637
+
638
+ return outputStrings;
639
+ }
640
+ }