Excel Export in ASP.NET MVC Tree Grid Component
29 Aug 20259 minutes to read
The excel export allows exporting TreeGrid data to Excel document. You need to use the excelExport method for exporting. To enable Excel export in the treegrid, set the AllowExcelExport as true.
@using Syncfusion.EJ2.Grids
@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
.Columns(col =>
{
col.Field("TaskId").HeaderText("Task ID").Width(90).TextAlign(TextAlign.Right).Add();
col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
col.Field("StartDate").HeaderText("Start Date").Format("yMd").Type("date").TextAlign(TextAlign.Right).Width(120).Add();
col.Field("Duration").HeaderText("Duration").Width(110).TextAlign(TextAlign.Right).Add();
}).Height(220).ChildMapping("Children").TreeColumnIndex(1).Toolbar(new List<string>() { "ExcelExport" })
.AllowExcelExport().AllowPaging().PageSettings(page => page.PageSize(7)).ToolbarClick("toolbarClick")
.Render()
)
<script>
function toolbarClick(args) {
if (args['item'].text === 'Excel Export') {
var treegrid = document.getElementById("TreeGrid").ej2_instances[0];
treegrid.excelExport();
}
}
</script>public IActionResult Index()
{
var tree = TreeData.GetDefaultData();
ViewBag.datasource = tree;
return View();
}Persist collapsed state
You can persist the collapsed state in the exported document by defining isCollapsedStatePersist property as true in TreeGridExcelExportProperties parameter of excelExport method.
@using Syncfusion.EJ2.Grids
@(Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.datasource)
.Columns(col =>
{
col.Field("TaskId").HeaderText("Task ID").Width(90).TextAlign(TextAlign.Right).Add();
col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
col.Field("StartDate").HeaderText("Start Date").Format("yMd").Type("date").TextAlign(TextAlign.Right).Width(120).Add();
col.Field("Duration").HeaderText("Duration").Width(110).TextAlign(TextAlign.Right).Add();
}).Height(220).ChildMapping("Children").TreeColumnIndex(1).Toolbar(new List<string>() { "ExcelExport" })
.AllowExcelExport().AllowPaging().PageSettings(page => page.PageSize(7)).ToolbarClick("toolbarClick")
.Render()
)
<script>
function toolbarClick(args) {
if (args['item'].text === 'Excel Export') {
var excelExportProperties = {
isCollapsedStatePersist: true
};
var treegrid = document.getElementById("TreeGrid").ej2_instances[0];
treegrid.excelExport(excelExportProperties);
}
}
</script>public IActionResult Index()
{
var tree = TreeData.GetDefaultData();
ViewBag.datasource = tree;
return View();
}Exporting custom aggregates in TreeGrid
The TreeGrid 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.
@Html.EJS().TreeGrid("TreeGrid").DataSource((IEnumerable<object>)ViewBag.DataSource).ChildMapping("subtasks").TreeColumnIndex(1).GridLines(Syncfusion.EJ2.Grids.GridLine.Both).AllowExcelExport(true).Toolbar(new List<string> { "ExcelExport", "CsvExport" }).Height(400).Width("auto").Columns(col =>
{
col.Field("ID").HeaderText("Order ID").Width(115).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Left).Add();
col.Field("Name").HeaderText("Shipment Name").Width(230).ClipMode(Syncfusion.EJ2.Grids.ClipMode.EllipsisWithTooltip).Add();
col.Field("shipmentDate").HeaderText("Shipment Date").Width(135).Type("date").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("category").HeaderText("Category").Width(220).MinWidth(210).Add();
col.Field("units").HeaderText("Total Units").Width(90).Type("number").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("unitPrice").HeaderText("Unit Price($)").Width(100).Type("number").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("price").HeaderText("Price($)").Width(140).Type("number").Format("C0").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
}).Aggregates(agg => { agg.ShowChildSummary(false).Columns(col => { col.Type("Custom").CustomAggregate("customAggregateFn").ColumnName("category").Format("C2").FooterTemplate("<span>Count of <input type='text' id='customers' /> : ${Custom}</span>").Add();}).Add();}).ExcelAggregateQueryCellInfo("formatExcelAggregateCell").DataBound("onDataBound").Render()
<script>
let selectedCategory = 'Seafood';
let categoryDropdown;
const categoryOptions = [
{ food: 'Seafood' },
{ food: 'Dairy' },
{ food: 'Edible' },
{ food: 'Crystal' },
];
function customAggregateFn(data) {
const records = data.result ? data.result : data;
return records.reduce((count, item) => {
return item.category === selectedCategory ? count + 1 : count;
}, 0);
}
function formatExcelAggregateCell(args) {
if (args.column.headerText === 'Category') {
args.style.value = `Count of ${selectedCategory} : ${args.data.category.Custom}`;
}
}
function onDataBound() {
if (categoryDropdown && categoryDropdown.element && categoryDropdown.element.classList.contains('e-dropdownlist')) {
categoryDropdown.destroy();
}
categoryDropdown = new ej.dropdowns.DropDownList({
dataSource: categoryOptions,
fields: { value: 'food' },
placeholder: 'Select a Category',
width: '110px',
value: selectedCategory,
change: () => {
setTimeout(() => {
if (categoryDropdown && categoryDropdown.value) {
selectedCategory = categoryDropdown.value.toString();
treeGridObj.refresh();
}
}, 300);
}
});
categoryDropdown.appendTo('#customers');
}
let treeGridObj;
document.addEventListener('DOMContentLoaded', function () {
treeGridObj = document.getElementById('TreeGrid').ej2_instances[0];
treeGridObj.toolbarClick = function (args) {
switch (args.item.text) {
case 'Excel Export':
treeGridObj.excelExport();
break;
case 'CSV Export':
treeGridObj.csvExport();
break;
}
};
});
</script>public IActionResult Index()
{
var tree = summaryData.GetDefaultData();
ViewBag.datasource = tree;
return View();
}
NOTE
You can refer to our
ASP.NET MVC Tree Gridfeature tour page for its groundbreaking feature representations. You can also explore ourASP.NET MVC Tree Grid exampleto knows how to present and manipulate data.