We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Export Grid by using API

Dear All

I try to export my grid data, I have the following challenges I was not able to find a solution by myself

I setup an Grid in my aspx page like this:

       <div id="mainTable" class="divMainGrid">
            <ej:Grid ID="mainGrid" Locale="de-DE" ClientIDMode="Static" AllowSorting="true" AllowScrolling="True" AllowFiltering="False" AllowTextWrap="True" 
                AllowPaging="true" AllowSearching="true" AllowResizing="true" EnableRowHover="False" OnServerExcelExporting="mainGrid_ServerExcelExporting"
                OnServerEditRow="mainGrid_ServerEditRow" IsResponsive="true" ShowDeleteConfirmDialog="true" AllowResizeToFit="true" runat="server">
                <DataManager Adaptor="WebApiAdaptor" Offline="true" URL="api/main" />
                <Columns>
                    <ej:Column Field="PHONENUMBER" HeaderText="PHONENUMBER" IsPrimaryKey="True" TextAlign="Right" Width="100">
                    </ej:Column>
                    <ej:Column Field="COUPLED_PHONENUMBER" HeaderText="COUPLED_PHONENUMBER" IsPrimaryKey="True" Width="100">
                </Columns>
                <ClientSideEvents ToolbarClick="onToolBarClick" />
                <ScrollSettings Height="660" Width="auto" />
                <ToolbarSettings ShowToolbar="True" ToolbarItems="excelExport,search,edit,cancel"></ToolbarSettings>
                <PageSettings PageSize="18" />
                <EditSettings AllowEditing="True" EditMode="DialogTemplate" DialogEditorTemplateID="#manual_reservation_template"></EditSettings>
                <SelectionSettings EnableToggle="true" />
                <FilterSettings FilterBarMode="Immediate" ShowFilterBarStatus="True" StatusBarWidth="300" FilterType="FilterBar"></FilterSettings>
            </ej:Grid>
        </div>


the data will be come by WebAPI, this works as expected.


Now I would export the data.


I tried this but was not able to find the correct way.

        protected void mainGrid_ServerExcelExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e)
        {
            ExcelExport exp = new ExcelExport();
            exp.Export(mainGrid.Model, (IEnumerable)mainGrid.DataManager.URL, "Export.xlsx", ExcelVersion.Excel2013, true, true, "flat-lime");
        }
 
In the export function itself I have no idea what I have to give as a second parameter, I can't set the mainGrid.DataSource because it is null, so what do I need to set here?


Thanks
Martin




3 Replies

SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team July 29, 2016 12:40 PM UTC

  
Hi Martin, 

Thanks for your interest in Syncfusion products. 

Since you have bound the remote data for the Grid, you cannot get the dataSource in the Grid instance. So we have suggest to handle the dataSource value for the export method explicitly.  

In two ways, you can assign a dataSource for the export method. You can define the datasource variable explicitly as shown in the following code example. We have assigned the same data to the export method as assigned to the Grid in the WebApi method. 

    <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> 
         
        <DataManager Adaptor="WebApiAdaptor" URL="/api/Orders" /> 
           . . .  
    </ej:Grid> 
 
    public class OrdersController : ApiController 
    { 
        // GET api/<controller> 
        NorthWndDataContext db = new NorthWndDataContext(); 
        public object Get() 
        { 
         . . .. .  
            var data = db.Orders; 
            return new { result = data.Skip(skip).Take(take), count = data.Count() }; 
        }  
         . . .  
    } 
 
 
    public partial class _Default : Page 
    { 
        NorthWndDataContext db = new NorthWndDataContext(); 
        protected void Page_Load(object sender, EventArgs e) 
        { 
            
        } 
        protected void Grid_ServerExcelExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e) 
        { 
            ExcelExport exp = new ExcelExport(); 
            exp.Export(Grid.Model, (IEnumerable)db.Orders, "Export.xlsx", ExcelVersion.Excel2010, true, true, "flat-lime"); 
        } 
          . . .  
    } 

Or else you can get the data that bound to the Grid using the Grid model and export them as shown in the following code example. In the Load event, we have spliced the dataSource from the ignoreOnExport array, which will include the dataSource on the Grid model while Exporting and it can be used for exporting the Grid as server end.  

    <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> 
 
        <DataManager Adaptor="WebApiAdaptor" URL="/api/Orders" Offline="true" /> 
           ..  . .  
        <ClientSideEvents Load="onLoad" /> 
    </ej:Grid> 
 
    <script> 
        function onLoad(args) { 
            this.ignoreOnExport.splice(this.ignoreOnExport.indexOf('dataSource'), 1); 
        } 
    </script> 
 
    public partial class _Default : Page 
    { 
        IEnumerable<Order> currentData; 
            . . . .  
        protected void Grid_ServerExcelExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e) 
        { 
            ExcelExport exp = new ExcelExport(); 
            string gridmodel = (string)e.Arguments.ToList()[0].Value; //collect the grid model 
             ConvertGridObject(gridmodel); //iterate and find the dataSource  
             exp.Export(Grid.Model, currentData, "Export.xlsx", ExcelVersion.Excel2010, true, true, "flat-lime"); 
        } 
        private void 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) 
            { 
 
                //Check and retrieve additional property here 
                if (ds.Key == "dataSource") 
                { 
                    foreach (KeyValuePair<string, object> data in (dynamic)ds.Value) 
                    { 
                        if (data.Key == "dataSource") { 
                            foreach (KeyValuePair<string, object> data1 in (dynamic)data.Value) 
                            { 
                                if (data1.Key == "json") { 
                                    string serial = serializer.Serialize(data1.Value); 
                                    currentData = JsonConvert.DeserializeObject<IEnumerable<Order>>(serial); 
                                    break; 
                                } 
 
                            } 
                        } 
                    } 
                    // 
                    break; 
                } 
            } 
        } 
    } 

We have prepared a sample that can be downloaded from the following location. 


Regards, 
Seeni Sakthi Kumar S. 



MS Martin Sickel August 3, 2016 06:36 AM UTC

Hi Seni

I have implemented the provided solution, but I am not able to get it working. In debug mode I can see that the data is there, but I end up with an error message.

Value cannot be null.
Parameter name: value

I add the code, maybe you can have a look what I am doing wrong.

Martin 

Attachment: SYNC_GRIDExportTest_e9f2c126.zip


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team August 4, 2016 12:15 PM UTC

Hi Chris,  

We are able to reproduce the problem with the provided sample. The cause of the problem is Key Value of the SearchSettings is not defined at the client end and on exporting the Grid Key with “null” value throws an exception. So we have modified our solution as follows. 

            <ej:Grid ID="mainGrid" ClientIDMode="Static" runat="server"> 
               . .   
            </ej:Grid> 
 
        protected void mainGrid_ServerExcelExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e) 
        { 
            try 
            { 
                ExcelExport export = new ExcelExport(); 
                string gridmodel = (string)e.Arguments.ToList()[0].Value; //collect the grid model  
                GridProperties gridProp = ConvertGridObject(gridmodel); //iterate and find the dataSource   
                export.Export(gridProp, (IEnumerable)currentData, "Export.xlsx", ExcelVersion.Excel2010, true, true, "flat-lime"); 
            } 
            catch (Exception exp) 
            { 
 
            } 
        } 
 
        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) 
            { 
 
                //Check and retrieve additional property here  
                if (ds.Key == "dataSource") 
                { 
                     . . . . . . . 
                } 
                else { 
                    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; 
        } 

Instead of passing the code behind Grid model to export method, we suggest to pass the grid model retrieved from client-side after deserializing them using the ConvertToGridObject(). Now ConvertToGridObject(), retrieves the dataSource as well as the grid model for export method. 

We have modified your sample that can downloaded from the following location. 


Regards, 
Seeni Sakthi Kumar S.  


Loader.
Live Chat Icon For mobile
Up arrow icon