Articles in this section
Category / Section

How to open excel file from local disk in Spreadsheet, when the file clicked in ejFileExplorer

3 mins read

Description

This knowledge base explains about how to open the excel file from local disk and view in ejSpreadsheet using ejFileExplorer.

Solution

JavaScript

 

HTML

<div id="fileExplorer"></div>
<div id="SpreadsheetDialog">
    <div style="height: 100%;">
        <div id="SpredsheetViewer"></div>
    </div>
</div>

 

JS

$("#fileExplorer").ejFileExplorer({
    fileTypes: "*.xls,*.xlsx ",
    layout: "tile",
    path: "D:/Spreadsheet/", //Physical path.
    ajaxAction: "Spreadsheet/FileAccess",
    width: "100%",
    minWidth: "150px",
    isResponsive: true,
    beforeOpen: "onBeforeOpen"
});
 
$("#SpreadsheetDialog").ejDialog({
    width: "80%",
    showOnInit: false
})
 
$("#SpredsheetViewer").ejSpreadsheet()
 
// Triggers before opening the file
function onBeforeOpen(args) {
    var ssDialog = $("#SpreadsheetDialog").data("ejDialog"), ssObj = $("#SpredsheetViewer").data("ejSpreadsheet");
    if (args.itemType == "File" && (/\.(xls|xlsx)$/i).test(args.selectedItems[0].name)) {
        var file = args.model.selectedFolder + args.model.selectedItems[0];
        $.ajax({
            url: "Spreadsheet/Import",
            type: "POST",
            dataType: "json",
            data: { filePath: file },
            success: function (data) {
                ssDialog.option("title", args.model.selectedItems[0]);
                ssDialog.open();
                ssObj.refresh();
                ssObj.loadFromJSON(data); // Load the JSON data to the spreadsheet
            }
        });
        args.cancel = true;
    }
}

 

WEBAPI

using Syncfusion.EJ.Export;
using Syncfusion.JavaScript;
using Syncfusion.JavaScript.Models;
 
// To process the import request.
[AcceptVerbs("Get", "Post")]
public HttpResponseMessage Import()
{
    string filePath = HttpContext.Current.Request.Params["filePath"];
    ImportRequest importRequest = new ImportRequest();
 
    //If the path from local drive.
    Stream fileStream = System.IO.File.Open(filePath, FileMode.Open, System.IO.FileAccess.Read);
    importRequest.FileStream = fileStream;
    var spreadsheetData = Spreadsheet.Open(importRequest);
    fileStream.Close();
    fileStream.Dispose();
    return new HttpResponseMessage() { Content = new StringContent(spreadsheetData, Encoding.UTF8, "text/plain") }; // Returns the Spreadsheet data
}
 
// To read the file in file explorer    
[AcceptVerbs("Get", "Post")]
public object FileAccess(FileExplorerParams args)
{
    FileExplorerOperations operation = new FileExplorerOperations();
    if (args.ActionType == "Read")
        return operation.Read(args.Path, args.ExtensionsAllow);
    else
        return string.Empty;
}

 

MVC

CSHTML

@(Html.EJ().FileExplorer("fileExplorer")
        .FileTypes("*.xls,*.xlsx")
        .Layout(LayoutType.Tile)
        .Path(@Url.Content("D:/Spreadsheet/"))  //Physical path.
        .AjaxAction(@Url.Action("FileAccess"))
        .Width("100%")
        .MinWidth("150px")
        .IsResponsive(true)
        .ClientSideEvents(eve => eve.BeforeOpen("onBeforeOpen"))
    )
 
@{Html.EJ().Dialog("SpreadsheetDialog").ContentTemplate(@<div style="height: 100%;">
    @{Html.EJ().Spreadsheet<object>("SpredsheetViewer").Render();}
</div>).Width("80%").ShowOnInit(false).Render();}
 
<script>
// Triggers before opening the file
    function onBeforeOpen(args) {
        var ssDialog = $("#SpreadsheetDialog").data("ejDialog"), ssObj = $("#SpredsheetViewer").data("ejSpreadsheet");
        if (args.itemType == "File" && (/\.(xls|xlsx)$/i).test(args.model.selectedItems[0])) {
            var file = args.model.selectedFolder + args.model.selectedItems[0];
            $.ajax({
                url: '@Url.Action("Import", "Home")',
                type: "POST",
                dataType: "json",
                data: { filePath: file },
                success: function (data) {
                    ssDialog.option("title", args.model.selectedItems[0]);
                    ssDialog.open();
                    ssObj.refresh();
                    ssObj.loadFromJSON(data); // Load the JSON data to the spreadsheet
                }
            });
            args.cancel = true;
        }
    }
</script>

 

Controller

using Syncfusion.EJ.Export;
using Syncfusion.JavaScript;
using Syncfusion.JavaScript.Models;
 
// To process the import request.
 [AcceptVerbs(HttpVerbs.Post)]
public ActionResult Import(ImportRequest importRequest, string filePath)
{
    //If the path from local drive.
    Stream fileStream = System.IO.File.Open(filePath, FileMode.Open, System.IO.FileAccess.Read);
    importRequest.FileStream = fileStream;
    var spreadsheetData = Spreadsheet.Open(importRequest);
    fileStream.Close();
    fileStream.Dispose();
    return Content(spreadsheetData); // Returns the Spreadsheet data
}
 
// To read the file in file explorer    
public ActionResult FileAccess(FileExplorerParams args)
{
    FileExplorerOperations operation = new FileExplorerOperations();
    if (args.ActionType == "Read")
        return Json(operation.Read(args.Path, args.ExtensionsAllow));
    else
        return Json(string.Empty);
}

 

ASP .NET

ASPX

<ej:FileExplorer ID="fileExplorer" runat="server" FileTypes="*.xls,*.xlsx" Layout="Tile"
    Path="D:/Spreadsheet/" AjaxAction="SpreadsheetFeatures.aspx/FileAccess" IsResponsive="true"
    Width="100%" MinWidth="150px" ClientSideOnBeforeOpen="onBeforeOpen">    
    <AjaxSettings>
        <Download Url="downloadFile.ashx{0}" />
        <Upload Url="uploadFiles.ashx{0}" />
    </AjaxSettings>
</ej:FileExplorer>
 
<ej:Dialog ID="SpreadsheetDialog" runat="server" Width="80%" ShowOnInit="false">
        <DialogContent>
            <div style="height: 100%;">
                <ej:Spreadsheet ID="SpredsheetViewer" runat="server">
                </ej:Spreadsheet>                               
            </div>
        </DialogContent>
</ej:Dialog>
 
<script type="text/javascript">
// Triggers before opening the file
    function onBeforeOpen(args) {
        var ssDialog = $("#SpreadsheetDialog").data("ejDialog"), ssObj = $("# SpredsheetViewer").data("ejSpreadsheet");
        if (args.itemType == "File" && (/\.(xls|xlsx)$/i).test(args.selectedItems[0].name)) {
            var file = args.model.selectedFolder + args.model.selectedItems[0];
            $.ajax({
                url: 'SpreadsheetHandler.ashx/ProcessRequest',
                type: "GET",
                dataType: "json",
                data: { filePath: file },
                success: function (data) {
                    ssDialog.option("title", args.model.selectedItems[0]);
                    ssDialog.open();
                    ssObj.refresh();
                    ssObj.loadFromJSON(data); // Load the JSON data to the spreadsheet
                }
            });
            args.cancel = true;
        }
    }
</script>

 

ASPX.CS

// To read the file in file explorer    
[WebMethod]
public static object FileAccess(string ActionType, string Path, string ExtensionsAllow)
{
    FileExplorerOperations operation = new FileExplorerOperations();
    if (ActionType == "Read")
        return (operation.Read(Path, ExtensionsAllow));
    else
        return string.Empty;
}

 

ASHX

using Syncfusion.EJ.Export;
using Syncfusion.JavaScript;
using Syncfusion.JavaScript.Models;
 
// To process the import request.
public void ProcessRequest(HttpContext context)
{
    var filePath = context.Request.QueryString[0];
    ImportRequest importRequest = new ImportRequest();
    Stream fileStream = File.Open(filePath, FileMode.Open, System.IO.FileAccess.Read);
    importRequest.FileStream = fileStream;
    importRequest.File = null;
    string str = Spreadsheet.Open(importRequest);
    fileStream.Close();
    fileStream.Dispose();
    context.Response.Write(str); // Returns the Spreadsheet data
}

 

spreadsheet file explorer sample preview

 

spreadsheet import request sample preview

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please sign in to leave a comment
Access denied
Access denied