@@ -3,7 +3,7 @@ import { MatTableDataSource } from '@angular/material/table';
33import { MatSort } from '@angular/material/sort' ;
44import { COMMA , ENTER } from '@angular/cdk/keycodes' ;
55import { FormControl } from '@angular/forms' ;
6- import * as XLSX from 'xlsx ' ;
6+ import * as ExcelJS from 'exceljs ' ;
77import { LoaderService } from 'src/app/service/loader/data-loader.service' ;
88import {
99 DialogInfo ,
@@ -157,12 +157,50 @@ export class MappingComponent implements OnInit, AfterViewInit {
157157 } ) ;
158158 }
159159
160- exportToExcel ( ) {
161- let element = document . getElementById ( 'excel-table' ) ;
162- const ws : XLSX . WorkSheet = XLSX . utils . table_to_sheet ( element , { raw : true } ) ;
163- const wb : XLSX . WorkBook = XLSX . utils . book_new ( ) ;
164- XLSX . utils . book_append_sheet ( wb , ws , 'Sheet1' ) ;
165- XLSX . writeFile ( wb , 'DSOMM - Activities.xlsx' ) ;
160+ async exportToExcel ( ) {
161+ const element = document . getElementById ( 'excel-table' ) ;
162+ if ( ! element ) {
163+ console . error ( 'Excel table element not found' ) ;
164+ return ;
165+ }
166+
167+ const workbook = new ExcelJS . Workbook ( ) ;
168+ const worksheet = workbook . addWorksheet ( 'Sheet1' ) ;
169+
170+ // Extract table data from HTML table
171+ const table = element as HTMLTableElement ;
172+ const rows = Array . from ( table . querySelectorAll ( 'tr' ) ) ;
173+
174+ rows . forEach ( ( row ) => {
175+ const cells = Array . from ( row . querySelectorAll ( 'th, td' ) ) ;
176+ const rowData = cells . map ( cell => cell . textContent ?. trim ( ) || '' ) ;
177+ worksheet . addRow ( rowData ) ;
178+ } ) ;
179+
180+ // Auto-fit columns for better readability
181+ worksheet . columns . forEach ( column => {
182+ let maxLength = 0 ;
183+ column . eachCell ?.( { includeEmpty : true } , ( cell ) => {
184+ const cellLength = cell . value ? cell . value . toString ( ) . length : 10 ;
185+ if ( cellLength > maxLength ) {
186+ maxLength = cellLength ;
187+ }
188+ } ) ;
189+ column . width = Math . min ( maxLength + 2 , 50 ) ; // Max width of 50
190+ } ) ;
191+
192+ // Generate and download the Excel file
193+ const buffer = await workbook . xlsx . writeBuffer ( ) ;
194+ const blob = new Blob ( [ buffer ] , {
195+ type : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
196+ } ) ;
197+ const url = window . URL . createObjectURL ( blob ) ;
198+ const anchor = document . createElement ( 'a' ) ;
199+ anchor . href = url ;
200+ anchor . download = 'DSOMM - Activities.xlsx' ;
201+ anchor . click ( ) ;
202+ window . URL . revokeObjectURL ( url ) ;
203+
166204 console . log ( `${ perfNow ( ) } : Mapping: Exported to Excel` ) ;
167205 }
168206
0 commit comments