export data (odata)

I'm using the datamanager with the odatav4adaptor and a remote odata-webservice.

this.data = new ej.DataManager({
url: "http://odataserver/data",
crossDomain: true,
adaptor: new ej.ODataV4Adaptor,
  });

When trying to export the data in the grid there is a call grid.export('/api/export/ExcelExport') to my export-webservice for exporting to Excelfile.
The problem is when the export-call arrives at the export-webservice the known parameter "gridModel" has no properties whichcan be usedto export the data (see below) .
My preferred solution is to get the odata-url from the datamanger, including the odata-parameters for select, expand, filter, orderby, top, skip, etc. (actually the full odata-url the datamanger has send to the odata-service). Is that possible? Or is there another solution for this?


{"allowPaging":true,"showColumnChooser":false,"gridLines":"both","allowSorting":true,"showStackedHeader":false,"selectedRecords":[],"stackedHeaderRows":[],"allowFiltering":true,"allowMultipleExporting":false,"allowSelection":true,"allowGrouping":false,"showSummary":false,"allowResizing":true,"allowResizeToFit":false,"allowTextWrap":false,"allowCellMerging":false,"enablePersistence":false,"enableFocusout":false,"selectedRowIndex":0,"selectedRowIndices":[0],"allowSearching":true,"enableToolbarItems":false,"allowReordering":true,"allowRowDragAndDrop":false,"enableTouch":true,"enableLoadOnDemand":false,"columnLayout":"auto","locale":"en-US{\\"EmptyRecord\\":\\"No records to display\\",\\"GroupCaptionFormat\\":\\"{{:headerText}}: {{:key}} - {{:count}} \\",\\"GroupText\\":\\" item\\",\\"True\\":\\"true\\",\\"False\\":\\"false\\"}","allowMultiSorting":true,"export
ToExcelAction":"ExportToExcel","exportToWordAction":"ExportToWord","exportToPdfAction":"ExportToPdf","_groupingCollapsed":[],"_isHeightResponsive":false,"_checkSelectedRowsIndexes":[[]],"selectionSettings":{"selectionMode":["row"],"enableToggle":false,"cellSelectionMode":"flow"},"resizeSettings":{"resizeMode":"normal"},"groupSettings":{"showDropArea":true,"showToggleButton":false,"showGroupedColumn":true,"showUngroupButton":true,"enableDropAreaAutoSizing":true,"captionFormat":null,"groupedColumns":[]},"contextMenuSettings":{"enableContextMenu":true,"contextMenuItems":["Add Record","Edit Record","Delete Record","Sort In Ascending Order","Sort In Descending Order","Next Page","Last Page","Previous Page","First Page","Save","Cancel","Grouping","Ungrouping"],"customContextMenuItems":[{"id":"1","text":"Add column"},{"id":"2","text":"Delete column"},{"id":"3","text":"Options..."}],"subContextMenu":[],"disa
bleDefaultItems":false},"filterSettings":{"filterType":"menu","filterBarMode":"immediate","showFilterBarStatus":true,"statusBarWidth":450,"showPredicate":false,"filteredColumns":[],"enableInterDeterminateState":true,"maxFilterChoices":1000,"enableCaseSensitivity":false,"immediateModeDelay":1500,"enableComplexBlankFilter":true,"blankValue":""},"searchSettings":{"fields":[],"key":"","operator":"contains","ignoreCase":true},"sortSettings":{"sortedColumns":[]},"toolbarSettings":{"showToolbar":true,"toolbarItems":["search"],"customToolbarItems":["Add","Refresh","Export","View"]},"minWidth":0,"currentIndex":0,"rowDropSettings":{"dragBehavior":"move","dropMapper":null,"dragMapper":null,"dropTargetID":null},"scrollSettings":{"width":1408,"height":0,"enableTouchScroll":true,"allowVirtualScrolling":false,"virtualScrollMode":"normal","frozenRows":0,"frozenColumns":0,"buttonSize":18,"autoHide":false,"scrollerSize":
18,"scrollOneStepBy":57,"enableVirtualization":false},"textWrapSettings":{"wrapMode":"both"},"summaryRows":[],"enableRTL":false,"enableAltRow":true,"detailsTemplate":null,"childGrid":null,"keySettings":null,"columns":[{"field":"id","headerText":"id","width":0,"visible":false,"isPrimaryKey":true,"allowResizing":true,"type":"number","textAlign":"left"},{"field":"code","headerText":"Code","width":100,"visible":true,"allowResizing":true,"type":"string","textAlign":"left"},{"field":"name","headerText":"Name","width":100,"visible":true,"allowResizing":true,"type":"string","textAlign":"left"},{"field":"program.name","headerText":"Program","width":100,"visible":true,"allowResizing":true,"type":"string","textAlign":"left"},{"field":"createdBy.name","headerText":"Created By","width":100,"visible":true,"allowResizing":true,"type":"string","textAlign":"left"},{"field":"createdOn","he
aderText":"Created On","width":100,"format":"{0:dd-MM-yyyy}","visible":true,"allowResizing":true,"type":"datetime","textAlign":"left"}],"isResponsive":false,"enableResponsiveRow":false,"virtualLoading":null,"keyConfigs":{"focus":"e","insertRecord":"45","deleteRecord":"46","editRecord":"113","saveRequest":"13","cancelRequest":"27","nextPage":"34","previousPage":"33","lastPage":"ctrl+alt+34","firstPage":"ctrl+alt+33","nextPager":"alt+34","previousPager":"alt+33","firstCellSelection":"36","lastCellSelection":"35","firstRowSelection":"ctrl+36","lastRowSelection":"ctrl+35","rowUpSelection":"ctrl+shift+38","rowDownSelection":"ctrl+shift+40","randomSelection":"ctrl+shift+83","upArrow":"38","downArrow":"40","rightArrow":"39","leftArrow":"37","moveCellRight":"9","moveCellLeft":"shift+9","selectedGroupExpand":"alt+40","totalGroupExpand":"ctrl+40","selectedGroupCollapse":"alt+38","
totalGroupCollapse":"ctrl+38","multiSelectionByUpArrow":"shift+38","multiSelectionByDownArrow":"shift+40","multiSelectionByRightArrow":"shift+39","multiSelectionByLeftArrow":"shift+37"}}

7 Replies

MP Manivannan Padmanaban Syncfusion Team February 22, 2018 02:36 PM UTC

Hi Sietse, 

We have analyzed your query and we are able to understand that you need to perform the exporting with the with the odatav4adaptor. We have  achieved your requirement by extend the OData adaptor please refer the below code example, 

<div id="Grid"></div> 
<script type="text/javascript"> 
    $(function () { 
        var customAdaptor = new ej.ODataV4Adaptor().extend({ 
            processResponse: function (data, ds, query, xhr, request, changes) { 
                result = this.base.processResponse.apply(this, [data, ds, query, xhr, request, changes]); 
               …….. 
                return result; 
            } 
        }); 
        var dataManager = new ej.DataManager({ 
            url: "/Odata/Orders/", adaptor: new ej.ODataV4Adaptor() 
        }); 
        $("#Grid").ejGrid({ 
            toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.ExcelExport, ej.Grid.ToolBarItems.WordExport, ej.Grid.ToolBarItems.PdfExport] }, 
            dataSource: dataManager, 
            columns: [ 
 
                     ……….. 
            ], 
            toolbarClick: function (e) { 
                this.exportGrid = this["export"]; 
                if (e.itemName == "Excel Export") { 
                    this.exportGrid("/Odata/Orders/ExcelExport") 
                    e.cancel = true; 
                } 
                else if (e.itemName == "Word Export") { 
                    this.exportGrid('/Odata/Orders /WordExport') 
                    e.cancel = true; 
                } 
                else if (e.itemName == "PDF Export") { 
                    this.exportGrid(‘/Odata/Orders /PdfExport') 
                    e.cancel = true; 
                } 
            }, 
        }); 
    }); 
</script> 
 
Controller Page: 
 
 
        [System.Web.Http.AcceptVerbs("Post")] 
        [ODataRoute("/ExcelExport")] 
 
public void ExcelExport() 
        { 
            GridExcelExport GridExp = new GridExcelExport(); 
            string gridModel = HttpContext.Current.Request.Params["GridModel"]; 
            GridProperties gridProperty = ConvertGridObject(gridModel); 
            ExcelExport exp = new ExcelExport(); 
            IEnumerable<Order> result = db.Orders.Take(100).ToList(); 
            GridExp.Theme = "default-theme"; 
            GridExp.FileName = "Export.xlsx"; 
            exp.Export(gridProperty, result, GridExp); 
        } 
 
[System.Web.Http.AcceptVerbs("Post")] 
        [ODataRoute("/PdfExport")] 
        public void PdfExport() 
        { 
            GridPdfExport GridExp = new GridPdfExport(); 
            string gridModel = HttpContext.Current.Request.Params["GridModel"]; 
            GridProperties gridProperty = ConvertGridObject(gridModel); 
            PdfExport exp = new PdfExport(); 
            IEnumerable<Order> result = db.Orders.Take(100).ToList(); 
            GridExp.Theme = "default-theme"; 
            GridExp.FileName = "Export.pdf"; 
            exp.Export(gridProperty, result, GridExp); 
        } 
 
[System.Web.Http.AcceptVerbs("Post")] 
        [ODataRoute("/WordExport")] 
        public void WordExport() 
        { 
            GridWordExport GridExp = new GridWordExport(); 
            string gridModel = HttpContext.Current.Request.Params["GridModel"]; 
            GridProperties gridPropert = ConvertGridObject(gridModel); 
            WordExport exp = new WordExport(); 
            IEnumerable<Order> data = db.Orders.Take(100).ToList(); 
            GridExp.Theme = "default-theme"; 
            GridExp.FileName = "Export.docx"; 
            exp.Export(gridPropert, (IEnumerable)data, GridExp); 
        }   
 
        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); 
                 
                ……… 
 
                value = serializer.Deserialize(serialize, type); 
                    property.SetValue(gridProp, value, null); 
                } 
            } 
            return gridProp; 
        } 
        
        


Please get back to us if you need any other information. 

Regards, 

Manivannan Padmanaban. 



SW Sietse Wielenga February 22, 2018 10:07 PM UTC

Hi

I already used the example, but the example-code in method ExcelExport takes some 100 records from the database, not exactly the data which is shown in the grid.
So, how do I get in method ExcelExport exactly the data which is shown in the grid?
Or is it possible to get the full odata-url (including $select, $filter, etc.) which is used in the datamanager?

[System.Web.Http.AcceptVerbs("Post")]
[ODataRoute("/ExcelExport")]
public void ExcelExport()
        {
            GridExcelExport GridExp = new GridExcelExport();
            string gridModel = HttpContext.Current.Request.Params["GridModel"];
            GridProperties gridProperty = ConvertGridObject(gridModel);
            ExcelExport exp = new ExcelExport(); 
            IEnumerable<Order> result = db.Orders.Take(100).ToList();
            GridExp.Theme = "default-theme";
            GridExp.FileName = "Export.xlsx";
            exp.Export(gridProperty, result, GridExp);
        }



RS Renjith Singh Rajendran Syncfusion Team February 23, 2018 01:22 PM UTC

Hi Sietse, 

Thanks for contacting Syncfusion support. 
 
We have analyzed your query and we found that you are trying to pass the data to server when exporting. You can get the data that is 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.  
 
Note: Please use load event to splice the dataSource 
 
Please refer the below code example. 
 
<script> 
     
   
    function load(args) { 
        this.ignoreOnExport.splice(this.ignoreOnExport.indexOf('dataSource'), 1); 
    } 
 
</script> 
public class HomeController : Controller 
    { 
        IEnumerable<EditableOrder> currentData = null; 
... 
    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) 
            { 
                //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<EditableOrder>>(serial); 
                                    break; 
                                } 
 
                            } 
                        } 
                    } 
                } 
... 
            return gridProp; 
        } 
 
 
Refer the documentation link. 
 
Please make a note that this solution works only for the local data. We have discussed about this in the following Help Document.  
 
Please let us know if you need further assistance. 
 
Regards, 
Renjith Singh Rajendran. 



SW Sietse Wielenga February 26, 2018 02:23 PM UTC

Hi,

Thank you for the explanation, but it does not met my needs because I don't want to use local data.
For getting the export data I would prefer using the full odata url (including $select, $filter and $orderby) which is used by the datamanager to retrieve the data in the grid.
So I figured out how to retrieve the full odata url from the odataadaptor and now I can pass it to the export-method.

export class BaseGridComponent implements OnInit {

private dataUrl: string = "";

ngOnInit(): void {

this.customAdaptor = new CustomOdataAdaptor();

this.customAdaptor.urlChanged = ((url: string) => {

this.dataUrl = url;

});

var dm = new ej.DataManager({

url: http://server/odata/entity,

crossDomain: true,

headers: [{ 'Accept': 'application/json' }, { 'Content-Type': 'application/json' }],

adaptor: this.customAdaptor

});

}

toolbarClick(args: any): void {

if (args.itemName == "Export") {

grid.export('/api/export/ExcelExport?odataurl=' + encodeURI(this.dataUrl));

args.cancel = true;

}

}

}

class CustomOdataAdaptor extends ej.ODataV4Adaptor {

constructor() {

super();

}

urlChanged: (url: string) => void;

beforeSend(dm, request, settings): void {

this.urlChanged(settings.url);

super.beforeSend(dm, request, settings);

}

processQuery(ds, query) {

return super.processQuery(ds, query);

}

processResponse(data, ds, query, xhr, request, changes) {

this.urlChanged(request.url);

return super.processResponse(data, ds, query, xhr, request, changes);

}

}




RS Renjith Singh Rajendran Syncfusion Team February 27, 2018 05:03 AM UTC

 
Thanks for the update. 
 
We are glad that you had to achieved your requirement. 
 
Please get back to us if you need further assistance. 
 
Regards, 
Renjith Singh Rajendran 




SP shekhar parate replied to Renjith Singh Rajendran March 19, 2018 05:21 AM UTC

Hi Sietse, 

Thanks for contacting Syncfusion support. 
 
We have analyzed your query and we found that you are trying to pass the data to server when exporting. You can get the data that is 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.  
 
Note: Please use load event to splice the dataSource 
 
Please refer the below code example. 
 
<script> 
     
   
    function load(args) { 
        this.ignoreOnExport.splice(this.ignoreOnExport.indexOf('dataSource'), 1); 
    } 
 
</script> 
public class HomeController : Controller 
    { 
        IEnumerable<EditableOrder> currentData = null; 
... 
    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) 
            { 
                //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<EditableOrder>>(serial); 
                                    break; 
                                } 
 
                            } 
                        } 
                    } 
                } 
... 
            return gridProp; 
        } 
 
 
Refer the documentation link. 
 
Please make a note that this solution works only for the local data. We have discussed about this in the following Help Document.  
 
Please let us know if you need further assistance. 
 
Regards, 
Renjith Singh Rajendran. 


Thanks for the information


FS Farveen Sulthana Thameeztheen Basha Syncfusion Team March 20, 2018 08:43 AM UTC

Hi Shekhar, 

Thanks for your update. Please get back to us if you need any further assistance. 

Regards, 

Farveen sulthana T 


Loader.
Up arrow icon