Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created August 25, 2021 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/16c772f40a913fd05a8095ae63bff248 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/16c772f40a913fd05a8095ae63bff248 to your computer and use it in GitHub Desktop.
Create, Read, and Edit Excel Spreadsheet in ASP.NET MVC

Read the complete article on creating ASP.NET MVC Spreadsheet application:

/* Add the following namespaces as well.
System.IO;
System.Collections;
System.Threading;
Microsoft.AspNetCore.StaticFiles;
Aspose.Cells.GridJs;
*/
[Route("[controller]/[action]")]
[ApiController]
public class GridJs2Controller : Controller
{
public ActionResult List()
{
//this.ViewBag.list = new List<object>();
ArrayList dirlistsss = new ArrayList();
ArrayList filelistsss = new ArrayList();
DirectoryInfo dir = new DirectoryInfo(TestConfig.ListDir);
//find files under the directory
FileInfo[] fi = dir.GetFiles();
foreach (FileInfo f in fi)
{
String fname = f.FullName.ToString();
dirlistsss.Add(fname);
filelistsss.Add(Path.GetFileName(fname));
}
// ViewData.
ViewBag.dirlist = dirlistsss;
ViewBag.filelist = filelistsss;
return View("~/Views/Home/list.cshtml");
}
// GET: /GridJs2/DetailJson?filename=
public ActionResult DetailFileJson(string filename)
{
String file = Path.Combine(TestConfig.ListDir, filename);
return DetailJson(file);
}
private ActionResult DetailJson(string path)
{
GridJsWorkbook wbj = new GridJsWorkbook();
try
{
GridInterruptMonitor m = new GridInterruptMonitor();
wbj.SetInterruptMonitorForLoad(m, 50 * 1000);
Thread t1 = new Thread(new ParameterizedThreadStart(InterruptMonitor));
t1.Start(new object[] { m, 90 * 1000 });
using (FileStream fs = new FileStream(path, FileMode.Open))
{
wbj.ImportExcelFile(fs, GridJsWorkbook.GetGridLoadFormat(Path.GetExtension(path)));
}
}
catch (Exception ex)
{
if (ex is GridCellException)
{
return Content(wbj.ErrorJson(((GridCellException)ex).Message + ((GridCellException)ex).Code), "text/plain", System.Text.Encoding.UTF8);
}
return Content(wbj.ErrorJson(ex.Message), "text/plain", System.Text.Encoding.UTF8);
}
//return File(stream, "application/octet-stream", "streamfile");
return Content(wbj.ExportToJson(), "text/plain", System.Text.Encoding.UTF8);
}
private static void InterruptMonitor(object o)
{
object[] os = (object[])o;
try
{
Thread.Sleep((int)os[1]);
((GridInterruptMonitor)os[0]).Interrupt();
}
catch (ThreadInterruptedException e)
{
Console.WriteLine("Succeeded for load in give time.");
}
}
[HttpPost]
// post: /GridJs2/UpdateCell
public ActionResult UpdateCell()
{
string p = HttpContext.Request.Form["p"];
string uid = HttpContext.Request.Form["uid"];
GridJsWorkbook gwb = new GridJsWorkbook();
String ret = gwb.UpdateCell(p, uid);
return Content(ret, "text/plain", System.Text.Encoding.UTF8);
}
// GET: /GridJs2/Xspreadtml
public ActionResult Xspreadtml(String filename)
{
return Redirect("~/xspread/index.html?file=" + filename);
}
// GET: /GridJs2/Image?uid=&id=
public FileResult Image()
{
string fileid = HttpContext.Request.Query["id"];
string uid = HttpContext.Request.Query["uid"];
return new FileStreamResult(GridJsWorkbook.GetImageStream(uid, fileid), "image/png");
}
//if use GridCacheForStream you need to set this api
// GET: /GridJs2/ImageUrl?uid=&id=
public JsonResult ImageUrl(string id, string uid)
{
return new JsonResult(GridJsWorkbook.GetImageUrl(uid, id, "."));
}
private string GetMimeType(string FileName)
{
string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(FileName, out contentType);
return contentType ?? "application/octet-stream";
}
// GET: /GridJs2/GetFile?id
public FileResult GetFile(string id)
{
string fileid = id;
string mimeType = GetMimeType(fileid);
return File(GridJsWorkbook.CacheImp.LoadStream(fileid), mimeType, fileid.Replace('/', '.'));
}
/// <summary>
/// down load file
/// </summary>
/// <returns></returns>
[HttpPost]
public JsonResult Download()
{
string p = HttpContext.Request.Form["p"];
string uid = HttpContext.Request.Form["uid"];
string filename = "123.xlsx";
GridJsWorkbook wb = new GridJsWorkbook();
wb.MergeExcelFileFromJson(uid, p);
GridInterruptMonitor m = new GridInterruptMonitor();
wb.SetInterruptMonitorForSave(m);
Thread t1 = new Thread(new ParameterizedThreadStart(InterruptMonitor));
t1.Start(new object[] { m, 30 * 1000 });
try
{
wb.SaveToCacheWithFileName(uid, filename, null);
}
catch (Exception ex)
{
if (ex is GridCellException)
{
return Json(((GridCellException)ex).Message + ((GridCellException)ex).Code);
}
}
if (filename.EndsWith(".html"))
{
filename += ".zip";
}
String fileurl = GridJsWorkbook.CacheImp.GetFileUrl(uid + "/" + filename);
return new JsonResult(fileurl);
}
}
public class HomeController : Controller
{
public IActionResult Index()
{
return RedirectToRoute("default",
new { controller = "GridJs2", action = "List" });
}
public IActionResult Privacy()
{
return Redirect("https://about.aspose.app/legal/privacy-policy");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
@{
ViewData["Title"] = "Home Page";
}
<div id="body" style=" width: 800px; height: 800px; border: 1px solid; overflow-y: scroll; SCROLLBAR-BASE-COLOR: #8ccc8c;">
@foreach (var item in ViewBag.filelist)
{
<a href="Xspreadtml?filename=@item" target="_blank"><em> @item </em> </a> <br />
}
</div>
/* Add the following namespaces as well.
using Aspose.Cells.GridJs;
using System.IO;
*/
public class LocalFileCache : GridCacheForStream
{
/// <summary>
/// Implement this method to savecache,save the stream to the cache object with the key id.
/// </summary>
/// <param name="s">the source stream </param>
/// <param name="uid">he key id.</param>
public override void SaveStream(Stream s, String uid)
{
String filepath = Path.Combine(Config.FileCacheDirectory + Path.DirectorySeparatorChar + "streamcache", uid.Replace('/', '.'));
using (FileStream fs = new FileStream(filepath, FileMode.Create))
{
s.Position = 0;
s.CopyTo(fs);
}
}
/// <summary>
/// Implement this method to loadcache with the key uid,return the stream from the cache object.
/// </summary>
/// <param name="uid">the key id</param>
/// <returns>the stream from the cache</returns>
public override Stream LoadStream(String uid)
{
String filepath = Path.Combine(Config.FileCacheDirectory + Path.DirectorySeparatorChar + "streamcache", uid.Replace('/', '.'));
FileStream fs = new FileStream(filepath, FileMode.Open);
return fs;
}
/// <summary>
/// implement the url in action controller to get the file
/// </summary>
/// <param name="uid">the key id</param>
/// <returns></returns>
public override String GetFileUrl(string uid)
{
return "/GridJs2/GetFile?id=" + uid;
}
}
/* Add the following namespace as well.
using Aspose.Cells.GridJs;
*/
License l = new License();
LocalFileCache mwc = new LocalFileCache();
GridJsWorkbook.CacheImp = mwc;
l.SetLicense(@"D:\licenses\Conholdate.Total.Product.Family.lic");
public class TestConfig
{
/// <summary>
/// the directory which contains workbook files
/// </summary>
internal static String ListDir = @"D:\tmpdel\storage\wb";
/// <summary>
/// temp directory to store files
/// </summary>
internal static String TempDir = @"D:\tmpdel\storage\wb\tmp\";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment