Search results

Excel Export in ASP.NET MVC Grid control

03 Aug 2021 / 6 minutes to read

The excel export allows exporting Grid data to Excel document. You need to use the excelExport method for exporting. To enable Excel export in the grid, set the AllowExcelExport property as true.

To use excel export, You need to define the ExcelExport in inbuild toolbar and define the ToolbarClick event for exporting the Grid.

razor
excel-export.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            gridObj.excelExport();
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Multiple Grid exporting

The excel export provides an option to export multiple grid data in the same excel file.

Same sheet

The excel export provides support to export multiple grids in same sheet. To export in same sheet, define multipleExport type as AppendToSheet in exportProperties. It have an option to provide blank rows between grids. These blank rows count can be defined by using the multipleExport as blankRows.

razor
same-sheet.cs
Copied to clipboard
@Html.EJS().Grid("FirstGrid").DataSource((IEnumerable<object>)ViewBag.FirstGridData).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

@Html.EJS().Grid("SecondGrid").DataSource((IEnumerable<object>)ViewBag.SecondGridData).AllowExcelExport().Columns(col =>
{
  col.Field("EmployeeID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("FirstName").Width("140").Add();
  col.Field("City").Width("120").Add();
  col.Field("Country").Width("140").Add();

}).AllowPaging().Render()

<script>
    function toolbarClick(args) {
        if (args.item.id === 'FirstGrid_excelexport') {
            var firstGrid = document.getElementById("FirstGrid").ej2_instances[0];
            var secondGrid = document.getElementById("SecondGrid").ej2_instances[0];
            var appendExcelExportProperties = {
                multipleExport: { type: 'AppendToSheet', blankRows: 2 }
            };

            var firstGridExport = firstGrid.excelExport(appendExcelExportProperties, true);
            firstGridExport.then((fData) => {
                secondGrid.excelExport(appendExcelExportProperties, false, fData);
            });
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    ViewBag.FirstGridData = OrderDetails.GetAllRecords();
    ViewBag.SecondGridData = EmployeeDetails.GetAllRecords();
    return View();
}

By default, multipleExport blankRows value is 5.

New Sheet

Excel exporting provides support to export multiple grids in new sheet. To export in new sheet, define multipleExport type as NewSheet in exportProperties.

razor
new-sheet.cs
Copied to clipboard
@Html.EJS().Grid("FirstGrid").DataSource((IEnumerable<object>)ViewBag.FirstGridData).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

@Html.EJS().Grid("SecondGrid").DataSource((IEnumerable<object>)ViewBag.SecondGridData).AllowExcelExport().Columns(col =>
{
   col.Field("EmployeeID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("FirstName").Width("140").Add();
   col.Field("City").Width("120").Add();
   col.Field("Country").Width("140").Add();

}).AllowPaging().Render()

<script>
    function toolbarClick(args) {
        if (args.item.id === 'FirstGrid_excelexport') {
            var firstGrid = document.getElementById("FirstGrid").ej2_instances[0];
            var secondGrid = document.getElementById("SecondGrid").ej2_instances[0];
            var appendExcelExportProperties = {
                multipleExport: { type: 'NewSheet' }
            };

            var firstGridExport = firstGrid.excelExport(appendExcelExportProperties, true);
            firstGridExport.then((fData) => {
                secondGrid.excelExport(appendExcelExportProperties, false, fData);
            });
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    ViewBag.FirstGridData = OrderDetails.GetAllRecords();
    ViewBag.SecondGridData = EmployeeDetails.GetAllRecords();
    return View();
}

To customize excel export

The excel export provides an option to customize mapping of the grid to excel document.

Export current page

The excel export provides an option to export the current page into excel. To export current page, define exportType to currentpage.

razor
export-current.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            var excelExportProperties = {
                exportType: 'CurrentPage'
            };
            gridObj.excelExport(excelExportProperties);
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Export hidden columns

The excel export provides an option to export hidden columns of grid by defining includeHiddenColumn as true.

razor
export-hidden.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").Visible(false).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            var excelExportProperties = {
                includeHiddenColumn: true
            };
            gridObj.excelExport(excelExportProperties);
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Show or Hide columns on Exported Excel

You can show a hidden column or hide a visible column while printing the grid using ToolbarClick and ExcelExportComplete events.

In the ToolbarClick event, based on args.item.id as Grid_excelexport. We can show or hide columns by setting Visible property of Column to true or false respectively.

In the ExcelExportComplete event, We have reversed the state back to the previous state.

In the below example, we have CustomerID as a hidden column in the grid. While exporting, we have changed CustomerID to visible column and ShipCity as hidden column.

razor
show-hide.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").ExcelExportComplete("excelExportComplete").Columns(col =>
{
  col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("CustomerID").HeaderText("Customer Name").Visible(false).Width("150").Add();
  col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
  col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
  col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            this.columns[1].visible = true;
            this.columns[3].visible = false;
            gridObj.excelExport();
        }
    }

    function excelExportComplete(args) {
        this.columns[1].visible = false;
        this.columns[3].visible = true;
    }

</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Export with filter options

The excel export provides an option to export with filter option in excel by defining enableFilter as true . It requires the allowFiltering to be true.

razor
enable-filter.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowFiltering(true).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").Visible(false).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            var excelExportProperties = {
                enableFilter: true
            };
            gridObj.excelExport(excelExportProperties);
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Conditional Cell Formatting

Grid cells in the exported Excel can be customized or formatted using ExcelQueryCellInfo event. In this event, we can format the grid cells of exported PDF document based on the column cell value.

In the below sample, we have set the background color for Freight column in the exported excel by using the arguments of ExcelQueryCellInfo event and backColor property.

razor
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().ExcelQueryCellInfo("excelQueryCellInfo").QueryCellInfo("queryCellInfo").Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            gridObj.excelExport();
        }
    }

    function excelQueryCellInfo(args) {
        if (args.column.field == 'Freight')
            if (args.value < 30) {
                args.style = { backColor: '#99ffcc' };
            }
            else if (args.value < 60) {
                args.style = { backColor: '#ffffb3' };
            }
            else {
                args.style = { backColor: '#ff704d' };
            }
    }

    function queryCellInfo(args) {
        if (args.column.field == 'Freight') {
            if (args.data['Freight'] < 30) {
                args.cell.bgColor = '#99ffcc';
            }
            else if (args.data['Freight'] < 60) {
                args.cell.bgColor = '#ffffb3';
            }
            else {
                args.cell.bgColor = '#ff704d';
            }
        }
    }
</script>

Theme

The excel export provides an option to include theme for exported excel document.

To apply theme in exported Excel, define the theme in ExcelExportProperties.

razor
theme.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            var excelExportProperties = {
                theme: {
                    header: { fontName: 'Segoe UI', fontColor: '#666666' },
                    record: { fontName: 'Segoe UI', fontColor: '#666666' },
                    caption: { fontName: 'Segoe UI', fontColor: '#666666' }
                }
            };
            gridObj.excelExport(excelExportProperties);
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

By default, material theme is applied to exported excel document.

The excel export provides an option to include header and footer content for exported excel document.

razor
header-footer.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            var excelExportProperties = {
                header: {
                    headerRows: 7,
                    rows: [
                        { cells: [{ colSpan: 4, value: "Northwind Traders", style: { fontColor: '#C67878', fontSize: 20, hAlign: 'Center', bold: true, } }] },
                        { cells: [{ colSpan: 4, value: "2501 Aerial Center Parkway", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] },
                        { cells: [{ colSpan: 4, value: "Suite 200 Morrisville, NC 27560 USA", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] },
                        { cells: [{ colSpan: 4, value: "Tel +1 888.936.8638 Fax +1 919.573.0306", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] },
                        { cells: [{ colSpan: 4, hyperlink: { target: 'https://www.northwind.com/', displayText: 'www.northwind.com' }, style: { hAlign: 'Center' } }] },
                        { cells: [{ colSpan: 4, hyperlink: { target: 'mailto:support@northwind.com' }, style: { hAlign: 'Center' } }] },
                    ]
                },
                footer: {
                    footerRows: 4,
                    rows: [
                        { cells: [{ colSpan: 4, value: "Thank you for your business!", style: { hAlign: 'Center', bold: true } }] },
                        { cells: [{ colSpan: 4, value: "!Visit Again!", style: { hAlign: 'Center', bold: true } }] }
                    ]
                },
            };
            gridObj.excelExport(excelExportProperties);
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

File Name for Exported document

You can assign the file name for the exported document by defining fileName property in ExcelExportProperties.

razor
export-filename.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            var excelExportProperties = {
                fileName: "new.xlsx"
            };
            gridObj.excelExport(excelExportProperties);
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Custom data source

The excel export provides an option to define datasource dynamically before exporting. To export data dynamically, define the dataSource in ExcelExportProperties.

razor
custom-data.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            var data = [
                { OrderID: "100", CustomerID: "Vinet", Freight: "2.00", OrderDate: new Date() },
                { OrderID: "101", CustomerID: "Hanar", Freight: "2.01", OrderDate: new Date() },
                { OrderID: "102", CustomerID: "Mega", Freight: "4.48", OrderDate: new Date() },
                { OrderID: "103", CustomerID: "Sam", Freight: "19.23", OrderDate: new Date() }
            ];
            var excelExportProperties = {
                dataSource: data
            };
            gridObj.excelExport(excelExportProperties);
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Exporting grouped records

The excel export provides outline option for grouped records which hides the detailed data for better viewing. In grid, we have provided the outline option for the exported document when the data’s are grouped.

razor
excel-group.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

}).AllowGrouping().GroupSettings(group => { group.Columns(new string[] { "CustomerID" }); }).AllowPaging().Toolbar(new List<string>() { "ExcelExport" }).Render()

<script>
    function toolbarClick(args) {
        var gridObj = document.getElementById("Grid").ej2_instances[0];
        if (args.item.id === 'Grid_excelexport') {
            gridObj.excelExport();
        }
    }
</script>
Copied to clipboard
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Export the hierarchy grid

The grid have an option to export the hierarchy grid to excel document. By default, grid will exports the visible child grids in expanded state. you can change the exporting option by using the hierarchyExportMode property of ExcelExportProperties. The available options are,

Mode Behavior
Expanded Exports the visible child grids in expanded state.
All Exports the all the child grids in expanded state.
None Exports all child grids in collapse state.
razor
hierarchy.cs
Copied to clipboard
@{
    var ChildGrid = new Syncfusion.EJ2.Grids.Grid() { DataSource = (IEnumerable<object>)ViewBag.DataSource,
      QueryString = "EmployeeID",
      Columns = new List<Syncfusion.EJ2.Grids.GridColumn>
      {
        new Syncfusion.EJ2.Grids.GridColumn(){ Field="OrderID", HeaderText="Order ID", Width="120" },
        new Syncfusion.EJ2.Grids.GridColumn(){ Field="Freight", HeaderText="Freight", Width="120", Format="C2", TextAlign=Syncfusion.EJ2.Grids.TextAlign.Right },
        new Syncfusion.EJ2.Grids.GridColumn(){ Field="ShipName", HeaderText="Ship Name", Width="150" },
        new Syncfusion.EJ2.Grids.GridColumn(){ Field="ShipCity", HeaderText="Ship City", Width="120" },
      }
   };
}
        
@Html.EJS().Grid("HierarchyExport").DataSource((IEnumerable<object>)ViewBag.EmpDataSource).AllowExcelExport().Columns(col =>
{
   col.Field("EmployeeID").HeaderText("Employee ID").Width("125").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("FirstName").HeaderText("Name").Width("125").Add();
   col.Field("Title").HeaderText("Title").Width("180").Add();
   col.Field("City").HeaderText("City").Width("135").Add();

}).AllowSorting().Toolbar(new List<string>() { "ExcelExport"}).ChildGrid(ChildGrid).ToolbarClick("toolbarClick").Render()

<script>
   function toolbarClick(args) {
       var gridObj = document.getElementById("HierarchyExport").ej2_instances[0];
       if (args.item.id === 'HierarchyExport_excelexport') {
            var excelExportProperties = {
                 hierarchyExportMode: "All"
            };
        gridObj.excelExport(excelExportProperties);
       }
   }
</script>
Copied to clipboard
public IActionResult Index()
{
    ViewBag.DataSource =  OrdersDetails.GetAllRecords();;
    ViewBag.EmpDataSource = EmployeeView.GetAllRecords();
    return View();
}

Limitations

  • Microsoft Excel permits up to seven nested levels in outlines. So that in the grid we can able to provide only up to seven nested levels and if it exceeds more than seven levels then the document will be exported without outline option. Please refer the Microsoft Limitation

Exporting Grid in server

The Grid have an option to export the data to Excel in server side using Grid server export library.

Server Dependencies

The Server side export functionality is shipped in the Syncfusion.EJ2.GridExport package, which is available in Essential Studio and nuget.org.The following list of dependencies is required for Grid server side Excel exporting action.

  • Syncfusion.EJ2
  • Syncfusion.EJ2.GridExport
  • Syncfusion.Compression.Base
  • Syncfusion.XlsIO.Base

Server Configuration

The following code snippets shows server configuration using ASP.NET MVC Controller Action.

To Export the Grid in server side, You need to call the serverExcelExport method for passing the Grid properties to server exporting action.

razor
server-exportMVC.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
    col.Field("Freight").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width("120").Add();  
}).Toolbar(new List<string>() { "ExcelExport" }).ToolbarClick("toolbarClick").Render()

<script>
    function toolbarClick(args) {
        var grid = document.getElementById("Grid").ej2_instances[0];
        grid.serverExcelExport("/Home/ExcelExport");
    }
</script>
Copied to clipboard
public ActionResult Index()
{
    var Order = OrdersDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}
public ActionResult ExcelExport(string gridModel)
{
    GridExcelExport exp = new GridExcelExport();
    Grid gridProperty = ConvertGridObject(gridModel);
    return exp.ExcelExport<OrdersDetails>(gridProperty, OrdersDetails.GetAllRecords());
}
private Grid ConvertGridObject(string gridProperty)
{
    Grid GridModel = (Grid)Newtonsoft.Json.JsonConvert.DeserializeObject(gridProperty, typeof(Grid));
    GridColumnModel cols = (GridColumnModel)Newtonsoft.Json.JsonConvert.DeserializeObject(gridProperty, typeof(GridColumnModel));
    GridModel.Columns = cols.columns;
    return GridModel;
}

public class GridColumnModel
{
    public List<GridColumn> columns { get; set; }
}

Note: Refer to the GitHub sample for quick implementation and testing from here.

CSV Export in server

You can export the Grid to CSV format by using the serverCsvExport method which will pass the Grid properties to server.

In the below demo, we have invoked the above method inside the toolbarClick event. In server side, we have deserialized the Grid properties and passed to the CsvExport method which will export the properties to CSV format.

razor
server-exportMVC.cs
Copied to clipboard
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
    col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
    col.Field("Freight").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width("120").Add();  
}).Toolbar(new List<string>() { "CsvExport" }).ToolbarClick("toolbarClick").Render()

<script>
    function toolbarClick(args) {
        var grid = document.getElementById("Grid").ej2_instances[0];
        grid.serverCsvExport("/Home/CsvGridExport");
    }
</script>
Copied to clipboard
public ActionResult Index()
{
    var Order = OrdersDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}
public ActionResult CsvGridExport(string gridModel)
{
    GridExcelExport exp = new GridExcelExport();
    Grid gridProperty = ConvertGridObject(gridModel);
    return exp.CsvExport<OrdersDetails>(gridProperty, OrdersDetails.GetAllRecords());
}
private Grid ConvertGridObject(string gridProperty)
{
    Grid GridModel = (Grid)Newtonsoft.Json.JsonConvert.DeserializeObject(gridProperty, typeof(Grid));
    GridColumnModel cols = (GridColumnModel)Newtonsoft.Json.JsonConvert.DeserializeObject(gridProperty, typeof(GridColumnModel));
    GridModel.Columns = cols.columns;
    return GridModel;
}