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
Unfortunately, activation email could not send to your email. Please try again.
Essential JS2

Syncfusion jQuery based widgets are no longer in active development. Switch to our pure JavaScript based next generation Essential JS 2 library.

Syncfusion Feedback

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

Platform: jQuery |
Control: ejSpreadSheet |
Published Date: July 31, 2018 |
Last Revised Date: May 22, 2019 |
.NET Framework: 4.5

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

ADD COMMENT
You must log in to leave a comment
Comments
Marco Giorgi
Dec 21, 2018

what is ImportRequest importRequest = new ImportRequest();

Guys, You have to specify what libraries we have to include otherwise this articles are useless!

Reply
Sangeetha Priya Murugan [Syncfusion]
Dec 24, 2018

Sorry for the inconvenience, we have modified the content based on your suggested namespace related changes.

Reply
Radouane Med
Dec 26, 2018

can you set  simple download of this code and for .docx ,.pdf

Reply
Akshaya Arivoli [Syncfusion]
Jan 02, 2019

Hi Radouane 

 

We can open the PDF document in the PDF viewer control while clicking PDF document from the FileExplorer control. Please find the KB for the same from the below,

 

https://www.syncfusion.com/kb/8733/viewing-pdf-documents-available-in-the-fileexplorer-control-using-pdf-viewer-control

 

Please let us know if you have any concerns on this.

 

Regards,

Akshaya

Reply
Mugunthan Anbalagan [Syncfusion]
Mar 06, 2019

Hi Radouane,


We can open the word document in the EJ2 DocumentEditor control, when the file clicked in ejFileExplorer. Please find the KB for the same from the below link.


https://www.syncfusion.com/kb/10176/how-to-open-a-word-document-available-in-the-file-explorer-control-using-documenteditor


Regards,

Mugunthan A

Reply

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile