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