Articles in this section
Category / Section

How to export current page/selected record in ASP.NET Web Forms Grid?

1 min read

 This KB showcase the example to export the current page/selected records from the Grid. In the ToolbarClick event, we have to update selected records or currentViewData into Grid model and export the Grid.

 

MVC Razor

@(Html.EJ().Grid<object>("ExportingGrid")
      .Datasource((IEnumerable<OrdersView>)ViewBag.datasource)
      .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); })
      .ToolbarSettings(tool => tool.ShowToolbar().ToolbarItems(item =>
       {
           item.AddTool(ToolBarItems.ExcelExport);
           item.AddTool(ToolBarItems.PdfExport);
           item.AddTool(ToolBarItems.WordExport);
       }))
       .AllowPaging()
      .Columns(col =>
        {
            col.Field("OrderID").Add();
            col.Field("CustomerID").Add();
            col.Field("EmployeeID").Add();
            col.Field("Freight").Format("{0:C2}").Add();
        })
      .ClientSideEvents(evt => evt.ToolbarClick("OnToolbarClick"))
)

 

<script>
    function OnToolbarClick(args) {
        if (args.itemName.indexOf("Export") > -1) {//if no selectedRecords, currenviewdata will be exported
            this.model["currentData"] = JSON.stringify(this.model.selectedRecords.length == 0 ? this.model.currentViewData : this.model.selectedRecords);
        }
    }
</script>

 

Controller

namespace MvcApplication66.Controllers
{
    public class HomeController : Controller
    {
        public IEnumerable currentData;
        public ActionResult Index(){
            var data = new NorthwindDataContext().OrdersViews.ToList();
            ViewBag.datasource = data;
            return View();
        }
            //Likewise perform exporting for pdf and word
        public void ExportToExcel(string GridModel)
        {
            ExcelExport exp = new ExcelExport();
            GridProperties obj = ConvertGridObject(GridModel);
            exp.Export(obj, currentData, "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 (ds.Key == "currentData")
                {
                    string str = Convert.ToString(ds.Value);
                    currentData = JsonConvert.DeserializeObject<IEnumerable<OrdersView>>(str);
                    continue;
                }
 
                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;
        }
    }

 

Likewise for ASP.Net Grid, retrieve the Grid model from the HttpContext. Refer the following code example.

 

ASPX

 

    <ej:Grid ID="FlatGrid" runat="server" OnServerWordExporting="WordExport" OnServerPdfExporting="PDFExport" OnServerExcelExporting="ExcelExport" AllowPaging="True">

        <ToolbarSettings ShowToolbar="true" ToolbarItems="excelExport,pdfExport,wordExport"></ToolbarSettings>

        <Columns>

            <ej:Column Field="OrderID" />

            <ej:Column Field="CustomerID" />

            <ej:Column Field="EmployeeID" />

            <ej:Column Field="Freight" Format="{0:C}" />

        </Columns>

        <ClientSideEvents ToolbarClick="onToolbarClick" />

    </ej:Grid>


 

 

ASPX.cs

    public partial class ExcelExporting : System.Web.UI.Page
    {
        public IEnumerable currentData;
        List<Orders> order = new List<Orders>();
        protected void Page_Load(object sender, EventArgs e)
        {
            BindDataSource();
        }
        [System.Web.Http.ActionName("ExcelExport")]
        [AcceptVerbs("POST")]
        public void ExcelExport()
        {
 
            string gridModel = HttpContext.Current.Request.Params["GridModel"];
 
            GridProperties gridPropert = ConvertGridObject(gridModel);
 
            ExcelExport exp = new ExcelExport();
 
            IEnumerable data = currentData;
 
            exp.Export(gridPropert, (IEnumerable)data, "Export.xlsx", ExcelVersion.Excel2010, false, false, "flat-azure-dark");
            //Likewise perform exporting for pdf and word
 
        }
        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);
  
                //Check and retrieve additional property here
                if (ds.Key == "currentData")
                {
                    string str = Convert.ToString(ds.Value);
                    currentData = JsonConvert.DeserializeObject<IEnumerable<OrdersView>>(str);
                    continue;
                }
                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;
        }
}

 

 

The following screenshot show Exported Grid and Grid with Exporting enabled.

Figure 1: CurrentViewData of Grid in Exported Excel

 

Figure 2: Exporting Grid


Note:

A new version of Essential Studio for ASP.NET is available. Versions prior to the release of Essential Studio 2014, Volume 2 will now be referred to as a classic versions.The new ASP.NET suite is powered by Essential Studio for JavaScript providing client-side rendering of HTML 5-JavaScript controls, offering better performance, and better support for touch interactivity. The new version includes all the features of the old version, so migration is easy.

The Classic controls can be used in existing projects; however, if you are starting a new project, we recommend using the latest version of Essential Studio for ASP.NET. Although Syncfusion will continue to support all Classic Versions, we are happy to assist you in migrating to the newest edition.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section 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