Having trouble getting help?
Contact Support
Contact Support
Import an excel document using file uploader in ASP.NET MVC Spreadsheet control
If you explore your machine to select and upload an excel document using the file uploader, you will receive the uploaded document as a raw file in the success
event of the file uploader. In this success
event, you should pass the received raw file as an argument to the Spreadsheet’s open
method to see the appropriate output.
The following code example shows how to import an excel document using file uploader in spreadsheet.
@Html.EJS().Uploader("UploadFiles").Success("onSuccess").AllowedExtensions(".xls, .xlsx, .csv").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Content("Home/Save"), RemoveUrl = @Url.Content("Home/Remove") }).Render()
@Html.EJS().Spreadsheet("spreadsheet").OpenUrl("Home/Open").Render()
<script>
function onSuccess(args) {
var ssObj = ej.base.getComponent(document.getElementById('spreadsheet'), 'spreadsheet');
if (args.operation === 'upload')
ssObj.open({ file: args.file.rawFile });
}
</script>
public IActionResult Open(IFormCollection openRequest)
{
OpenRequest open = new OpenRequest();
open.File = openRequest.Files[0];
return Content(Workbook.Open(open));
}
public void Save(IList<IFormFile> UploadFiles)
{
long size = 0;
try
{
foreach (var file in UploadFiles)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = hostingEnv.WebRootPath + $@"\{filename}";
size += file.Length;
if (!System.IO.File.Exists(filename))
{
using (FileStream fs = System.IO.File.Create(filename))
{
//file.CopyTo(fs);
//fs.Flush();
}
}
else
{
using (FileStream fs = System.IO.File.Open(filename, FileMode.Append))
{
//file.CopyTo(fs);
//fs.Flush();
}
}
}
}
catch (Exception e)
{
Response.Clear();
Response.StatusCode = 204;
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
}
}
public void Remove(string UploadFile)
{
try
{
var filename = hostingEnv.WebRootPath + $@"\{UploadFile}";
if (System.IO.File.Exists(filename))
{
System.IO.File.Delete(filename);
}
}
catch (Exception e)
{
Response.Clear();
Response.StatusCode = 200;
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully";
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
}
}