Articles in this section
Category / Section

How to modify ASP.NET Core Grid properties while exporting?

1 min read

Solution:

 

We can modify all the ASP.NET Core Grid properties at server end while on Exporting, For instance, we have removed the specific columns on Excel Export and similarly it can be followed in other types of grid exporting such as PDF Export. To achieve this, we can get the columns from the Grid properties and remove it by using Remove property of c#.

 

1. Render the Grid.

 

JS

<div id="Grid"></div>
<script type="text/javascript">
    $(function () {// Document is ready.
        $("#Grid").ejGrid({
            dataSource: window.gridData,
            allowPaging: true,
            toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.ExcelExport, ej.Grid.ToolBarItems. WordExport, ej.Grid.ToolBarItems. PdfExport] },
            columns: [
                      { field: "OrderID", headerText: "Order ID", isPrimaryKey: true, width: 100},
                      { field: "CustomerID", headerText: "Customer ID", width: 100 },
                      { field: "Freight", headerText: "Freight", width: 100, format: "{0:C}" },
                      { field: "ShipCountry", headerText: "Ship Country", width: 100,  }
            ],
        toolbarClick: function (e) {
            this.exportGrid = this["export"];
            if (e.itemName == "Excel Export") {
                this.exportGrid('/Grid/ExportToExcel ')
                e.cancel = true;
            }
            else if (e.itemName == "Word Export") {
                this.exportGrid('/Grid/ExportToWord ')
                e.cancel = true;
            }
            else if (e.itemName == "PDF Export") {
                this.exportGrid('/Grid/ExportToPdf ')
                e.cancel = true;
            }
        },
        });
    });
</script>

 

 

MVC

@(Html.EJ().Grid<object>("FlatGrid")
         .Datasource((IEnumerable<object>)ViewBag.datasource)
         .AllowPaging()    /*Paging Enabled*/
                  
        .ToolbarSettings(toolBar => toolBar.ShowToolbar().ToolbarItems(items =>
         {
             items.AddTool(ToolBarItems.ExcelExport);
             items.AddTool(ToolBarItems.WordExport);
             items.AddTool(ToolBarItems.PdfExport);
         }))
        .Columns(col =>
        {
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(100).Add();
            col.Field("CustomerID").HeaderText("Customer ID").Width(100).Add();
         col.Field("Freight").HeaderText("Freight").Width(100).Format("{0:C}").Add();
            col.Field("ShipCountry").HeaderText("Ship Country").Width(100).Add();
 
        }))
 
 

 

 

ASP

[aspx]
<ej:Grid ID="Grid" runat="server" AllowPaging="True"       OnServerWordExporting="Grid_ServerWordExporting" OnServerPdfExporting="Grid_ServerPdfExporting" OnServerExcelExporting="Grid_ServerExcelExporting">  
             <ToolbarSettings ShowToolbar="True" ToolbarItems="excelexport,wordexport,pdfexport"></ToolbarSettings>           
            <Columns>
               <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="True"  Width="100" />                
                <ej:Column Field="CustomerID" HeaderText="Customer ID" Width="100"/>
                <ej:Column Field="Freight" HeaderText="Freight" Format="{0:C}" Width="100"/> 
                <ej:Column Field="ShipCountry" HeaderText="Ship Country" Width="100"/>                
            </Columns>
</ej:Grid>
 

 

ASP.NET Core

<ej-grid id="FlatGrid" allow-paging="true" datasource="ViewBag.DataSource" >
     <e-toolbar-settings show-toolbar="true" toolbar-items='@new List<string> {"add","edit","update","cancel"}' />
    <e-columns>
        <e-column field="OrderID" is-primary-key="true" header-text="Order ID" width="100"></e-column>
        <e-column field="CustomerID" header-text="Customer ID" width="100"></e-column>
        <e-column field="Freight" header-text="Freight" width="100" format="{0:C}"></e-column>
         <e-column field="ShipCountry" header-text="Ship Country" width="100"></e-column>
        
    </e-columns>
</ej-grid>
 

 

codeBehind

MVC

   public class GridController : Controller
        {
           
            public ActionResult Index()
            {
                ViewBag.datasource = new NorthwindDataContext().OrdersViews.Take(100).ToList();
                return View();
            }    
          public void ExportToExcel(string GridModel)
            {
            ExcelExport exp = new ExcelExport();
            var DataSource = new NorthwindDataContext().OrdersViews.Take(100).ToList();
            GridProperties obj = ConvertGridObject(GridModel);
            Column remCol = obj.Columns.Where(col => col.Field == "OrderID").ToList()[0];  // get the column from Grid properties
            obj.Columns.Remove(remCol); // remove column using Remove property of c#      
            exp.Export(obj, DataSource, "Export.xlsx", ExcelVersion.Excel2010, false, false, "flat-saffron");
            }
        
         private GridProperties ConvertGridObject(string gridProperty) {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            IEnumerable div = (IEnumerable)serializer.Deserialize(gridProperty, typeof(IEnumerable));
            GridProperties gridProp = new GridProperties();
            foreach (KeyValuePair<string, object> ds in div)
            {
                var property = gridProp.GetType().GetProperty(ds.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                if (property != null)
                {
                    Type type = property.PropertyType;
                    string serialize = serializer.Serialize(ds.Value);
                    object value = serializer.Deserialize(serialize, type);
                    property.SetValue(gridProp, value, null);
                }
            }
            return gridProp;
        }
    }
 

 

ASP

Protected void Grid_ServerExcelExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e)
        {
             ExcelExport exp = new ExcelExport();
             var DataSource = new NorthwindDataContext().OrdersViews.ToList();
             GridProperties obj = ConvertGridObject(GridModel);
             Column remCol = obj.Columns.Where(col => col.Field == "OrderID").ToList()[0];     // get the column from Grid properties
 
             obj.Columns.Remove(remCol); // remove column using Remove property of c#      
             exp.Export(obj, (IEnumerable)Grid.DataSource, "Export.xlsx", ExcelVersion.Excel2010, false, false, "flat-saffron");
        }
  

 

ASP.NET Core

    public class HomeController : Controller
    {
        public static List<Orders> order = new List<Orders>();
 
        public IActionResult Index()
        {
            ViewBag.datasource = order;
            return View();
        }
 
        public ActionResult ExportToExcel(string GridModel)
        {
            ExcelExport exp = new ExcelExport();
            var DataSource =order;
            GridProperties gridProp = ConvertGridObject(GridModel);
            Column remCol = obj.Columns.Where(col => col.Field == "OrderID").ToList()[0];     // get the column from Grid properties
            obj.Columns.Remove(remCol); // remove column using Remove property of c#      
            excelExp.Theme = "flat-saffron";
            return exp.Export(gridProp, DataSource, excelExp);
        }
 

 

Output Screenshot:

 

At Excel Exporting:-

Conclusion

I hope you enjoyed learning about how to modify ASP.NET Core Grid properties while exporting.

You can refer to our  ASP.NET Core Grid feature tour page to know about its other groundbreaking feature representations. You can also explore our  ASP.NET Core Grid examples to understand how to present and manipulate data.

For current customers, you can check out our ASP.NET Core Controls from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our ASP.NET Core DataGrid and other ASP.NET Core controls.

If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied