Excel export in Angular TreeGrid component
24 Sep 202524 minutes to read
Excel export in the TreeGrid component enables exporting TreeGrid data to an Excel document. The excelExport
method is used for exporting data. To enable Excel export in TreeGrid, set the allowExcelExport
property to true.
Inject the ExcelExport
module into the TreeGrid to use the Excel export feature.
Watch this video to learn how to perform exporting operations and customize them in Angular TreeGrid.
import { NgModule,ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid'
import { PageService, ExcelExportService, ToolbarService } from '@syncfusion/ej2-angular-treegrid'
import {ButtonModule} from '@syncfusion/ej2-angular-buttons'
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns'
import { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { ToolbarItems } from '@syncfusion/ej2-treegrid';
import { ExcelExportProperties } from '@syncfusion/ej2-grids';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
imports: [
TreeGridModule,
ButtonModule,
DropDownListAllModule,
],
providers: [PageService,
ExcelExportService,
ToolbarService],
standalone: true,
selector: 'app-container',
template: `<ejs-treegrid [dataSource]='data' #treegrid height='220' (toolbarClick)='toolbarClick($event)' [allowPaging]='true' [allowExcelExport]='true' [pageSettings]='pager' [treeColumnIndex]='1' childMapping='subtasks' [toolbar]='toolbarOptions'>
<e-columns>
<e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
<e-column field='taskName' headerText='Task Name' textAlign='Left' width=180></e-column>
<e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=120></e-column>
<e-column field='duration' headerText='Duration' textAlign='Right' width=110></e-column>
</e-columns>
</ejs-treegrid>`
})
export class AppComponent implements OnInit {
public data?: Object[];
public pager?: Object;
@ViewChild('treegrid')
public treeGridObj?: TreeGridComponent;
public toolbarOptions?: ToolbarItems[];
ngOnInit(): void {
this.data = sampleData;
this.pager = { pageSize: 7 };
this.toolbarOptions = ['ExcelExport'];
}
toolbarClick(args: Object | any) : void {
if (args['item'].text === 'Excel Export') {
this.treeGridObj?.excelExport();
}
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
Show spinner while exporting
Showing a spinner while exporting in the TreeGrid enhances the experience by displaying a spinner during the export process. This feature provides a visual indication of the export progress, improving the understanding of the exporting process.
To show or hide a spinner while exporting theTreeGrid, you can utilize the showSpinner and hideSpinner methods provided by the TreeGrid within the toolbarClick event.
The toolbarClick
event is triggered when a toolbar item in the TreeGrid is clicked. Within the event handler, the code checks if the clicked item is related with Excel export. If a match is found, the showSpinner
method is used on the TreeGrid instance to display the spinner.
To hide the spinner after the exporting is completed, bind the excelExportComplete event and use the hideSpinner
method on the TreeGrid instance to hide the spinner.
The following example demonstrates how to show and hide the spinner during Excel export in a TreeGrid.
import { NgModule,ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid'
import { PageService, SortService, FilterService } from '@syncfusion/ej2-angular-treegrid'
import {ButtonModule} from '@syncfusion/ej2-angular-buttons'
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns'
import { Component, OnInit, ViewChild } from '@angular/core';
import { projectData } from './datasource';
import { TreeGridComponent, ToolbarItems, ToolbarService, PageService, ExcelExportService } from '@syncfusion/ej2-angular-treegrid';
import { ClickEventArgs } from '@syncfusion/ej2-angular-navigations';
@Component({
imports: [
TreeGridModule,
ButtonModule,
DropDownListAllModule
],
providers: [PageService,
SortService,
FilterService],
standalone: true,
selector: 'app-container',
providers: [ToolbarService, PageService, ExcelExportService],
template: `<ejs-treegrid #treegridObj [dataSource]='data' idMapping='TaskID' parentIdMapping='parentID'
[treeColumnIndex]='1' [allowPaging]='true' [pageSettings]='initialPage' [toolbar]='toolbarOptions' [allowExcelExport]='true' (excelExportComplete)='excelExportComplete()' (toolbarClick)='toolbarClick($event)'>
<e-columns>
<e-column field='TaskID' headerText='Task ID' width='70' textAlign='Right'></e-column>
<e-column field='TaskName' headerText='Task Name' width='100' ></e-column>
<e-column field='StartDate' headerText='Start Date' textAlign='Right' [format]='formatOptions' width='100'></e-column>
<e-column field='EndDate' headerText='Start Date' textAlign='Right' [format]='formatOptions'width='100'></e-column>
<e-column field='Duration' headerText='Duration' width='90' textAlign='Right'></e-column>
<e-column field='Priority' headerText='Priority' width='90'></e-column>
</e-columns>
</ejs-treegrid>`,
})
export class AppComponent implements OnInit {
public data: Object[] = [];
public formatOptions?: Object;
public toolbarOptions?: ToolbarItems[];
public initialPage?: object;
@ViewChild('treegridObj')
public treegridObj?: TreeGridComponent;
ngOnInit(): void {
this.data = projectData;
this.formatOptions = { format: 'y/M/d', type: 'date' };
this.toolbarOptions = ['ExcelExport'];
this.initialPage = { pageCount: 5, pageSize: 5 };
}
toolbarClick(args: ClickEventArgs) {
if (this.treegridObj && args.item.text === 'Excel Export') {
this.treegridObj.showSpinner();
this.treegridObj.excelExport();
}
}
excelExportComplete() {
if (this.treegridObj) {
this.treegridObj.hideSpinner();
}
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
Persisting collapsed state
The collapsed state of nodes in the exported Excel document can be persisted by setting the isCollapsedStatePersist
property to true within the TreeGridExcelExportProperties
parameter of the excelExport
method.
import { NgModule,ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid'
import { PageService, ExcelExportService, ToolbarService } from '@syncfusion/ej2-angular-treegrid'
import {ButtonModule} from '@syncfusion/ej2-angular-buttons'
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns'
import { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { ToolbarItems, TreeGridExcelExportProperties } from '@syncfusion/ej2-treegrid';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
imports: [
TreeGridModule,
ButtonModule,
DropDownListAllModule,
],
providers: [PageService,
ExcelExportService,
ToolbarService],
standalone: true,
selector: 'app-container',
template: `<ejs-treegrid [dataSource]='data' #treegrid height='220' (toolbarClick)='toolbarClick($event)' [allowPaging]='true' [allowExcelExport]='true' [pageSettings]='pager' [treeColumnIndex]='1' childMapping='subtasks' [toolbar]='toolbarOptions'>
<e-columns>
<e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
<e-column field='taskName' headerText='Task Name' textAlign='Left' width=180></e-column>
<e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=120></e-column>
<e-column field='duration' headerText='Duration' textAlign='Right' width=110></e-column>
</e-columns>
</ejs-treegrid>`
})
export class AppComponent implements OnInit {
public data?: Object[];
public pager?: Object;
@ViewChild('treegrid')
public treeGridObj?: TreeGridComponent;
public toolbarOptions?: ToolbarItems[];
ngOnInit(): void {
this.data = sampleData;
this.pager = { pageSize: 7 };
this.toolbarOptions = ['ExcelExport'];
}
toolbarClick(args: Object | any) : void {
if (args['item'].text === 'Excel Export') {
let excelExportProperties: TreeGridExcelExportProperties = {
isCollapsedStatePersist: true
};
this.treeGridObj?.excelExport(excelExportProperties);
}
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
The CSV export feature allows exporting TreeGrid data to a text document. Use the
csvExport
method for exporting. To enable CSV export in TreeGrid, set theallowCsvExport
property to true.
Custom data source
Excel export provides the capability to define a data source dynamically before exporting. To export data dynamically, assign a value to the dataSource
property in exportProperties
.
import { NgModule,ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid'
import { PageService, ExcelExportService, ToolbarService } from '@syncfusion/ej2-angular-treegrid'
import {ButtonModule} from '@syncfusion/ej2-angular-buttons'
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns'
import { Component, OnInit } from '@angular/core';
import { sampleData } from './datasource';
import { ToolbarItems } from '@syncfusion/ej2-treegrid';
import { ExcelExportProperties } from '@syncfusion/ej2-grids';
import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid';
@Component({
imports: [
TreeGridModule,
ButtonModule,
DropDownListAllModule,
],
providers: [PageService,
ExcelExportService,
ToolbarService],
standalone: true,
selector: 'app-container',
template: `<ejs-treegrid [dataSource]='data' #treegrid height='220' (toolbarClick)='toolbarClick($event)' [allowPaging]='true' [allowExcelExport]='true' [pageSettings]='pager' [treeColumnIndex]='1' childMapping='subtasks' [toolbar]='toolbarOptions'>
<e-columns>
<e-column field='taskID' headerText='Task ID' textAlign='Right' width=90></e-column>
<e-column field='taskName' headerText='Task Name' textAlign='Left' width=180></e-column>
<e-column field='startDate' headerText='Start Date' textAlign='Right' format='yMd' width=120></e-column>
<e-column field='duration' headerText='Duration' textAlign='Right' width=110></e-column>
</e-columns>
</ejs-treegrid>`
})
export class AppComponent implements OnInit {
public data?: Object[];
public pager?: Object;
@ViewChild('treegrid')
public treeGridObj?: TreeGridComponent;
public toolbarOptions?: ToolbarItems[];
ngOnInit(): void {
this.data = sampleData;
this.pager = { pageSize: 7 };
this.toolbarOptions = ['ExcelExport'];
}
toolbarClick(args: Object | any) : void {
if (args['item'].text === 'Excel Export') {
let excelExportProperties: ExcelExportProperties = {
dataSource: sampleData
};
this.treeGridObj?.excelExport(excelExportProperties);
}
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
Exporting Custom Aggregates in Tree Grid
The Tree Grid enables exporting custom aggregates, which summarize column data, to an Excel document using the ExcelAggregateQueryCellInfo
event.
In the provided example, the customAggregateFn function computes the item count for a selected category, while the ExcelAggregateQueryCellInfo
event customizes the exported cell values in the Excel document.
import { Component, OnInit, ViewChild } from '@angular/core';
import { summaryData } from './datasource';
import { getObject, PdfExportProperties } from '@syncfusion/ej2-angular-grids';
import { TreeGridComponent, TreeGridAllModule, ToolbarItems } from '@syncfusion/ej2-angular-treegrid';
import { isNullOrUndefined } from '@syncfusion/ej2-base';
import { DropDownList } from '@syncfusion/ej2-angular-dropdowns';
@Component({
selector: 'app-container',
template: `<ejs-treegrid #treegrid [dataSource]='dataSource' gridLines="Both" height='350' childMapping='subtasks' [allowPdfExport]='true' [toolbar]='toolbarOptions' (toolbarClick)='toolbarClick($event)'
[allowExcelExport]='true' [treeColumnIndex]='1' (dataBound)='onDataBound($event)' (excelAggregateQueryCellInfo)="excelAggregateQueryCellInfo($event)">
<e-columns>
<e-column field='ID' headerText='Order ID' width='120' textAlign='Left'></e-column>
<e-column field='Name' headerText='Shipment Name' textAlign="Left" clipMode='EllipsisWithTooltip' width='230' ></e-column>
<e-column field='shipmentDate' headerText='Shipment Date' width="120" type="date" format="yMd" textAlign="Right"></e-column>
<e-column field='category' headerText='Category' width='200' minWidth='240' textAlign="Left" ></e-column>
<e-column field='units' headerText='Units' width='80' type='number' textAlign="Right" ></e-column>
<e-column field='unitPrice' headerText='Unit Price($)' width='120' type='number' textAlign="Right" format='C2' ></e-column>
<e-column field='price' headerText='Price($)' width='110' type='number' format='C0' textAlign="Right" ></e-column>
</e-columns>
<e-aggregates >
<e-aggregate [showChildSummary]='false'>
<e-columns >
<e-column columnName="category" type="Custom" [customAggregate]="customAggregateFn">
<ng-template #footerTemplate let-data>
<span>Count of <input type="text" id="customers" /> : </span>
</ng-template>
</e-column>
</e-columns>
</e-aggregate>
</e-aggregates>
</ejs-treegrid>`,
standalone: true,
imports: [TreeGridAllModule],
})
export class AppComponent {
public dataSource: Object[] = [];
public foods: any;
public selectedCategory: string = 'Seafood';
public listObj!: DropDownList;
public toolbarOptions?: ToolbarItems[];
public customAggregateFn!: (data: Object) => number;
public countLength: number = 0;
public stringAlign: string = 'Left';
public numberAlign: string = 'Right';
@ViewChild('treegrid')
public treegrid!: TreeGridComponent;
ngOnInit(): void {
this.dataSource = summaryData;
this.foods = [
{ food: 'Seafood' },
{ food: 'Dairy' },
{ food: 'Edible' },
{ food: 'Crystal' },
];
this.toolbarOptions = ['ExcelExport', 'CsvExport'];
this.customAggregateFn = this.createCustomAggregateFn(
this.selectedCategory
);
}
//Custom aggregate function to calculate the count of items for the selected category.
private createCustomAggregateFn(
selectedValue: string
): (data: Object) => number {
return (data: Object): number => {
const sampleDatas: any = getObject('result', data) ?? data;
return sampleDatas
? sampleDatas.filter(
(item: Object) => getObject('category', item) === selectedValue
).length
: 0;
};
}
//Handles the 'excelAggregateQueryCellInfo' event to customize aggregate cells during Excel export.
public excelAggregateQueryCellInfo = (args: any): void => {
if (args.cell.column.headerText === 'Category') {
args.style.value =
'Count of ' +
this.selectedCategory +
' : ' +
args.row.data.category.Custom;
}
};
//Initializes a DropDownList in the footer for category selection.
onDataBound(args: any): void {
if (!isNullOrUndefined(this.listObj)) {
this.listObj.destroy();
}
var proxy = this;
this.listObj = new DropDownList({
dataSource: proxy.foods,
fields: { value: 'food' },
placeholder: 'Select a Category',
width: '110px',
value: this.selectedCategory,
change: () => {
setTimeout(() => {
this.selectedCategory = (this.listObj as any).value.toString();
proxy.selectedCategory = this.selectedCategory;
proxy.customAggregateFn = proxy.createCustomAggregateFn(
proxy.selectedCategory
);
proxy.treegrid.refresh();
}, 300);
},
});
this.listObj.appendTo('#customers');
}
toolbarClick(args: Object | any): void {
if (args['item'].text === 'Excel Export') {
this.treegrid?.excelExport();
} else if (args['item'].text === 'CSV Export') {
this.treegrid?.csvExport();
}
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
Passing additional parameters to the server while exporting
Passing additional parameters to the server when exporting data in the Syncfusion Angular TreeGrid involves providing flexibility to include extra information or customize the export process based on specific requirements.
You can achieve this by utilizing the query property and the toolbarClick event. Within the query property, you can invoke the addParams method to add parameters to the request.
The following example demonstrates how to pass additional parameters to the server when Excel exporting within the toolbarClick
event. Within the event, the additional parameters, specifically recordcount as 12, are passed using the addParams
method and displayed as a message.
import { NgModule,ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { TreeGridModule } from '@syncfusion/ej2-angular-treegrid'
import { PageService, SortService, FilterService } from '@syncfusion/ej2-angular-treegrid'
import {ButtonModule} from '@syncfusion/ej2-angular-buttons'
import { DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns'
import { Component, OnInit, ViewChild } from '@angular/core';
import { projectData } from './datasource';
import { TreeGridComponent, ToolbarItems, ToolbarService, PageService, ExcelExportService } from '@syncfusion/ej2-angular-treegrid';
import { Query } from '@syncfusion/ej2-data';
import { ClickEventArgs } from '@syncfusion/ej2-angular-navigations';
@Component({
imports: [
TreeGridModule,
ButtonModule,
DropDownListAllModule
],
providers: [PageService, SortService, FilterService],
standalone: true,
selector: 'app-container',
providers: [ToolbarService, PageService, ExcelExportService],
template: `<ejs-treegrid #treegridObj [dataSource]='data' idMapping='TaskID'
parentIdMapping='parentID' [treeColumnIndex]='1' [allowPaging]='true' [pageSettings]='initialPage'
[toolbar]='toolbarOptions' [allowExcelExport]='true'
(excelExportComplete)='excelExportComplete()'
(toolbarClick)='toolbarClick($event)'>
<e-columns>
<e-column field='TaskID' headerText='Task ID' width='70' textAlign='Right'></e-column>
<e-column field='TaskName' headerText='Task Name' width='100' ></e-column>
<e-column field='StartDate' headerText='Start Date' textAlign='Right' [format]='formatOptions' width='100'></e-column>
<e-column field='EndDate' headerText='Start Date' textAlign='Right' [format]='formatOptions'width='100'></e-column>
<e-column field='Duration' headerText='Duration' width='90' textAlign='Right'></e-column>
<e-column field='Priority' headerText='Priority' width='90'></e-column>
</e-columns>
</ejs-treegrid>`,
})
export class AppComponent implements OnInit {
public data: Object[] = [];
public formatOptions?: Object;
public toolbarOptions?: ToolbarItems[];
public initialPage?: object;
public queryClone?: any;
@ViewChild('treegridObj')
public treegridObj?: TreeGridComponent;
ngOnInit(): void {
this.data = projectData;
this.formatOptions = { format: 'y/M/d', type: 'date' };
this.toolbarOptions = ['ExcelExport'];
this.initialPage = { pageCount: 5, pageSize: 5 };
}
toolbarClick(args: ClickEventArgs) {
if (this.treegridObj && args.item.text === 'Excel Export') {
this.queryClone = this.treegridObj.query;
this.treegridObj.query = new Query().addParams("recordcount", "12");
this.treegridObj.excelExport();
}
}
excelExportComplete() {
if (this.treegridObj) {
this.treegridObj.query = this.queryClone;
}
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
For more information, refer to the
Angular TreeGrid
feature tour page. You can also explore theAngular TreeGrid example
to discover how to present and manipulate data.