New to Telerik UI for ASP.NET MVC? Download free 30-day trial

Spreadsheet Load an Excel File From Controller

Environment

Product Version 2023.3.1010
Product Telerik UI for ASP.NET MVC Spreadsheet

Description

I have a .xlsx file on the server and need to load it by default in the Spreadsheet after it initializes.

Solution

  1. Save the file in the wwwroot/files directory of the project.
  2. Configure the Controller and an Action method that access the file and returns it in JSON format by using the Telerik.Web.Spreadsheet dependency.

            using Telerik.Web.Spreadsheet;
    
            public class SpreadsheetController : Controller
            {
                public ActionResult ReadFile()
                {
                    var path = Server.MapPath("~/App_Data/Docs/document.xlsx");
                    var workbook = Telerik.Web.Spreadsheet.Workbook.Load(path);
    
                    //Uses Newtonsoft.Json internally to serialize fields correctly.
                    return Content(workbook.ToJson(), Telerik.Web.Spreadsheet.MimeTypes.JSON);
                }
            }
    
  3. Set up an Ajax request to the ReadFile Action method and consume the JSON of the response with the use of the fromJSON() method.

        function readFile(){
            $.ajax({
                url: "@Url.Action("ReadFile","Spreadsheet")",
                success: function (e) {
                    var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet");
                    spreadsheet.fromJSON(e);
                },
                error: function (er) {
                    console.log(er);
                }
            })
        }
    

Review the complete implementation and test the behavior at our Examples repo in GitHub.

More ASP.NET MVC Spreadsheet Resources

See Also

In this article