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

Spreadsheet Load an Excel File From Controller

Environment

Product Version 2023.3.1010
Product Telerik UI for ASP.NET Core 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
                {
    
                    private readonly IWebHostEnvironment _hostingEnvironment;
    
                    public SpreadsheetController(IWebHostEnvironment hostingEnvironment)
                    {
                        _hostingEnvironment = hostingEnvironment;
                    }
    
                    public IActionResult ReadFile()
                    {
                        string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "files", "Exported.xlsx");
                        var exists = System.IO.File.Exists(filePath);
                        if (System.IO.File.Exists(filePath))
                        {
                            Stream fileStream = System.IO.File.OpenRead(filePath);
                            var workbook = Workbook.Load(fileStream, Path.GetExtension(filePath));
                            return Content(workbook.ToJson(), Telerik.Web.Spreadsheet.MimeTypes.JSON);
                        }
                        else
                        {
                            return Content("File doesn't exist.");
                        }
                    }
            }
    
  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 Core Spreadsheet Resources

See Also

In this article