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 from View to Controller to Excel

Hi there,

I want to export a displaye4d Grid exactly as it is to Excel.

From the demos and samples I have looked at, I cannot see how this is possible, because all the demo go something like this...


public void ExportToExcel(string GridModel)

{

     ExcelExport exp = new ExcelExport();

     var DataSource = new NorthwindDataContext().OrdersViews.ToList();

     GridProperties obj = ConvertGridObject(GridModel);

     exp.Export(obj, DataSource"Export.xlsx"ExcelVersion.Excel2010, falsefalse,"bootstrap-theme");

}

var DataSource = new NorthwindDataContext().OrdersViews.ToList() is just loading the data again... this is not what I require.

How do I have a Grid on my View, click a button and pass that grid exactly as is to the Action to be used as the Datasource?

If I use the following method, how do I pass the Grid's data as dataSource parameter?

public void ExportToExcel(string GridModel, IEnumerable dataSource)

{

     var exp = new ExcelExport();

   var DataSource = dataSource;

   var obj = ConvertGridObject(GridModel);

    exp.Export(obj, DataSource, "Export.xlsx", ExcelVersion.Excel2010, false, false, "default-theme");

}

regards,

N. Jamieson




4 Replies

NE Neill May 18, 2017 10:29 AM UTC

Any replies?

I have not got it working using a separate button for exporting, but have got it working using the Excel Export Toolbar button/icon.

Finding this article helped me solve it:

https://www.syncfusion.com/kb/6331/how-to-export-current-page-selected-record 

My solution.

Controller:

        public IEnumerable currentData;

        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<MockAnatomyLinked>>(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;
        }

Razor (cshtml)

<div class="col-lg-6" id="datagrid">
        @if (ViewBag.datasource != null)
        {
            @(Html.EJ().Grid<EngineeringAssistantMVC.Controllers.AnatomyController.MockAnatomyLinked>("RowSelection")
                .Datasource((IEnumerable<object>)ViewBag.datasource).AllowSorting().AllowPaging()
                .AllowFiltering()
                .FilterSettings(filter => { filter.FilterType(FilterType.Excel); })
                .AllowGrouping()
                .EnableAltRow(true)
                .IsResponsive()
                .ToolbarSettings(tool => tool.ShowToolbar().ToolbarItems(item =>
                {
                    item.AddTool(ToolBarItems.ExcelExport);
                }))
                .Columns(col =>
                {
                    col.Field("AnatomyLinkedId").HeaderText("ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(20).Add();
                    col.Field("SerialNumber").HeaderText("Serial Number").Width(60).Add();
                    col.Field("ParentId").HeaderText("Parent ID").Width(60).Add();
                    col.Field("Description").HeaderText("Description").Width(60).Add();
                    col.Field("LinkStation").HeaderText("Link Station").Width(60).Add();
                    col.Field("DateLinked").HeaderText("Date Linked").Width(60).Priority(2).Format("{0:dd/MM/yyyy}").Add();
                    col.Field("UnlinkStation").HeaderText("Unlink Station").Width(60).Add();
                    col.Field("DateUnlinked").HeaderText("Date Unlinked").Width(60).Priority(2).Format("{0:dd/MM/yyyy}").Add();
                    col.Field("User").HeaderText("User").Width(60).Add();
                })
                .ClientSideEvents(events =>
                {
                    events.RecordClick("RecordsClick");
                    events.ActionComplete("OnActionComplete");
                    events.ToolbarClick("OnToolbarClick");

                })
            )
        }
    </div>

Javascript:

<script type="text/javascript">

    function OnToolbarClick(args) {
        this.model["currentData"] = JSON.stringify(this.model.currentViewData);
    }
</script>

If you Filter the results, only the filtered results are exported as well, which is cool.
Hope it helps somebody else wanting to export the grid as is, without reloading data in the method.

Regards,

Neill


MS Mani Sankar Durai Syncfusion Team May 18, 2017 10:34 AM UTC

Hi Neil, 

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. 
@(Html.EJ().Grid<object>("FlatGrid") 
                .Datasource((IEnumerable<object>)ViewBag.dataSource) 
        .AllowPaging() 
        .ToolbarSettings(toolBar => toolBar.ShowToolbar(true).ToolbarItems(items => 
            { 
                items.AddTool(ToolBarItems.ExcelExport); 
                items.AddTool(ToolBarItems.PdfExport); 
                items.AddTool(ToolBarItems.WordExport); 
            })) 
                .Columns(col => 
            { 
                ... 
            }) 
          .ClientSideEvents(evt =>evt.Load("load")) 
) 
 
<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; 
        } 
 
 
Based on your requirement we have prepared a sample that can be downloaded from the below link. 
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, 
Manisankar Durai. 



NE Neill May 18, 2017 10:38 AM UTC

Thank you for the response,

For some reason your response did not display until after I replied having sorted out my issue.

Regards,

Neill


MS Mani Sankar Durai Syncfusion Team May 19, 2017 05:33 AM UTC

Hi Neil, 

Thanks for the update. 

Please try our solution and get back to us if you need any further assistance. 

Regards, 
Manisankar Durai 


Loader.
Live Chat Icon For mobile
Up arrow icon