Completed
Last Updated: 03 Nov 2015 18:14 by ADMIN
Brad
Created on: 17 Nov 2011 13:58
Category: Kendo UI for jQuery
Type: Feature Request
22
Export Grid to Excel.
I imagine this would be difficult, but it's a feature that we would most certainly need if we ever were to make this our primary framework...  A server-side excel file could be generated as-is, but the problem is that users expect the document to be identical to the grid they are viewing.  If they do any filtering/grouping/sorting, they expect the resulting excel document to match.  The current Telerik winforms RadGridView does a wonderful job at this and produces an xml excel document - this would be the ideal behavior to duplicate..
Duplicated Items
13 comments
ADMIN
Telerik Admin
Posted on: 03 Nov 2015 18:14
This is already supported. See this demo for reference:

http://demos.telerik.com/kendo-ui/grid/excel-export
Ankit
Posted on: 20 Dec 2012 06:32
How i gave custom color to excel sheet header and group header ?
Mark Hynes
Posted on: 27 Sep 2012 20:56
Couldn't you write an access method to generate some kind of xml representation of all filters in place so that could be sent back to the server to generate the excel export?
loi
Posted on: 03 Aug 2012 01:09
Here was my complete implementation of CSV export using the ServiceStack.Text and Json.Net libraries. This maybe helpful to some people :]

//ServiceStack.Text library (https://github.com/ServiceStack/ServiceStack.Text)
//Json.Net library (http://json.codeplex.com)

/***** Controller Action *******/

        public FileContentResult CourtDateSearchResultToCsv(string searchResultJson)
        {
            List<CourtCalendarQueryRecord> searchResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CourtCalendarQueryRecord>>(searchResultJson);
            string csv = "";
            if (searchResult != null)
            {
                //covert all datetime values to proper date string for before conversion.
                var formatResult = searchResult.Select(o => new
                {
                    CourtCaseNumber = o.CourtCaseNumber,
                    ScheduledDate = o.ScheduledDateTime.ToShortDateString(),
                    ScheduledTime = o.ScheduledDateTime.ToString("hh:mmtt"),
                    HearingType = o.HearingType
                });
                
                //serialize objects collection to csv string
                csv = ServiceStack.Text.CsvSerializer.SerializeToString(formatResult);
            }
            byte[] csvBytes = ASCIIEncoding.ASCII.GetBytes(csv);
            return File(csvBytes, "text/csv", "CourtDateSearchResultData.csv");
        }


/***** VIEW *******/

<script type="text/javascript">

		function doCourtDateCsvExport(){
			var resultJsonData = $("#CourtCalendarGrid").data("tGrid").data;
			if (resultJsonData.length > 0) {
			    if ($.browser.msie == true) //fix IE min-date serialization issue
			        $("#CourtCalendarGrid_searchResultJson").val( JSON.stringify(resultJsonData).replace(/01-01-01T08:00:00Z/gi, "0001-01-01T08:00:00Z") );
			    else
			        $("#CourtCalendarGrid_searchResultJson").val(JSON.stringify(resultJsonData));

				$("#CourtCalendarGrid_CsvForm").submit();
			}
			else {
				alert("Sorry, there is no data to export.");
			}
		}
		
</script>


@(Html.Telerik().Grid<CourtCalendarQueryRecord>()
    .ToolBar(toolBar => toolBar.Template(
        @<text>
				<button class='t-button t-button-icon t-button-bare' title='Export to Excel' onclick='doCourtDateCsvExport()' > <img src='/images/icons/application_go.gif' alt='' />Export To Excel </button>                           
        </text>
    ))
    .Name("CourtCalendarGrid")
    .Sortable(sorting => sorting.SortMode(GridSortMode.SingleColumn))
    .DataBinding(dataBinding => dataBinding.Ajax().Select("_GetCourtCalendar", "Home", new { forCurrentUser = ViewBag.ForCurrentUser}).OperationMode(GridOperationMode.Client))
    .Columns(columns =>
    {
        columns.Bound(o => o.ScheduledDate).Title("Date").Width(120).ClientTemplate("<#= ScheduledDateDisplay #>");
        columns.Bound(o => o.ScheduledTime).Title("Time");        
        columns.Bound(o => o.CourtCaseNumber).Title("CR Number");
        columns.Bound(o => o.ClientName).Title("Client Name");
    })
)

<form method="post" action="@Url.Action("CourtDateSearchResultToCsv", "Search")" id="CourtCalendarGrid_CsvForm")">
	<input type="hidden" name="searchResultJson" id="CourtCalendarGrid_searchResultJson")" />
</form>
Gary
Posted on: 31 Jul 2012 18:40
It is fairly easy to implement, using .Net MVC, create a controller action like this: 

[ValidateInput(false)]
        [HttpPost]
        public ActionResult XLSHandler(string html)
        {
            try
            {
                string h = HttpUtility.UrlDecode(html);
                string filename = DateTime.Now.Ticks.ToString() + ".xls";
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                return File(encoding.GetBytes(h), "application/vnd.ms-excel", filename);
            }
            catch (Exception e)
            {
                //handle error
                return View();
            }
        }

Then in your javascript you should create a hidden form, and when they click the export button, populate the input on the form with the HTML from the grid, then submit the form to the controller action:

function exportGrid(){
        var h = $("#grid").html();
        $("#html").val(h);
        $("#myForm").submit();
    }

<form id="myForm" action="@Url.Action("XLSHandler", "Report")" method="post">
<input type="hidden" id="html" name="html" />
</form>
Wannes
Posted on: 16 Jul 2012 15:11
Actually, I think all the tools are almost there:
1. First the developer creates an Excel/Word document and saves it as Office XML.
2. The developer puts kendoui template placeholder in the XML.
3. The JS app will load the template with Ajax and then apply the JSON values to it.

The only missing part is a way to offer this endresult to the user... For example, I wouldn't know how to set a content-type header in a new window with JavaScript.

An alternative would be to create a server-side component with the same Office XML templates and to let KendoUI send its data to the server which will then set the content-type and content-disposition headers for downloading the file.
Dan
Posted on: 08 Feb 2012 10:11
I guess you would need a server side end point (MVC controller or otherwise) that would take all the current grid data in JSON (or XML) and then be responsible for generating and sending the resulting Excel file back to the client?
ADMIN
Telerik Admin
Posted on: 25 Jan 2012 09:53
Thanks for sharing these resources, we will look into them.
Justin
Posted on: 24 Jan 2012 00:30
All you need to do is convert the JSON from the grid into CSV http://stackoverflow.com/questions/4130849/convert-json-format-to-csv-format-for-ms-excel
ADMIN
Telerik Admin
Posted on: 20 Dec 2011 09:01
We will consider exposing server-side extensions for the Kendo UI widgets for the future versions of the framework. Then it will most likely be possible to implement export functionality using the server extensions.
Tony
Posted on: 20 Dec 2011 01:37
Shouldn't be too hard to create the server side wrappers in various platforms. It will make it really hard to replace grid based apps built with Datatables, Jqgrid or  most other grids on the market. For me this means the grid will most likely only be usable for front-end purposes. All of my clients are used to being able to export the data seen in the grids. Even the beta Datatables provides a plugin for multiple export formats.

This is meat and potatoes...so to speak for developing custom web apps, CMS and other admin functionality. I hope the dev team is not going to dismiss this as too difficult as it would likely limit the grids use in serious apps.
ADMIN
Telerik Admin
Posted on: 05 Dec 2011 14:45
Can you please elaborate further on how this xml is supposed to be transmit via javascript and offered to the user? Do you happen to encounter a solution implemented in javascript which does exactly what you depicted? We will appreciate a reference to it, if exists.
Brad
Posted on: 05 Dec 2011 13:31
If you generated the xml with javascript(which I know is possible), you could leave it up to us to do what we need to do with it..

Off the top of my head, I could see a javascript method post to another page that basically takes in the xml and offers it back to the user to download.. Seems a little redundant, but it would get the job done..

Please reconsider this..