翻譯|使用教程|編輯:李顯亮|2021-08-27 09:35:57.917|閱讀 297 次
概述:在本文中,您將學習如何在ASP.NET MVC 應用程序中創(chuàng)建、讀取和編輯 Excel 電子表格。為此,我們將創(chuàng)建一個由功能豐富的網格控件組成的電子表格應用程序,用于顯示和編輯 Excel 文件。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
在本文中,您將學習如何在ASP.NET MVC 應用程序中創(chuàng)建、讀取和編輯 Excel 電子表格。為此,我們將創(chuàng)建一個由功能豐富的網格控件組成的電子表格應用程序,用于顯示和編輯 Excel 文件,如下所示:
為了在 ASP.NET MVC 中創(chuàng)建電子表格應用程序,我們將使用Aspose.Cells.GridJs。API 允許您創(chuàng)建基于 Web 的應用程序以快速輕松地顯示或編輯電子表格文檔。此外,您可以導入流行的電子表格(XLS、XLSX、XLSM、XLSB、CSV、SpreadsheetML、ODS)文件格式(閱讀更多)。此外,它還提供了強大而豐富的公式計算引擎,不僅可以計算內置函數,還可以計算自定義公式。
以下是在 ASP.NET MVC 中創(chuàng)建基于 Web 的電子表格應用程序的步驟。
1、在 Visual Studio 中創(chuàng)建一個新的ASP.NET Core Web 應用程序(模型-視圖-控制器)。
2、從 NuGet安裝Aspose.Cells.GridJs。
3、將以下代碼插入到HomeController.cs 中。
public class HomeController : Controller { public IActionResult Index() { return RedirectToRoute("default", new { controller = "GridJs2", action = "List" }); } public IActionResult Privacy() { return Redirect("http://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 }); } }
4、在Models文件夾中新建一個名為TestConfig.cs 的類,并添加以下代碼(根據您的環(huán)境更改文件夾路徑)。
public class TestConfig { ////// the directory which contains workbook files ///internal static String ListDir = @"D:\tmpdel\storage\wb"; ////// temp directory to store files ///internal static String TempDir = @"D:\tmpdel\storage\wb\tmp\"; }
5、在Models文件夾中創(chuàng)建一個名為LocalFileCache.cs的新類并添加以下代碼。
/* Add the following namespaces as well. using Aspose.Cells.GridJs; using System.IO; */ public class LocalFileCache : GridCacheForStream { ////// Implement this method to savecache,save the stream to the cache object with the key id. //////the source stream///he key id.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); } } ////// Implement this method to loadcache with the key uid,return the stream from the cache object. //////the key id///the stream from the cachepublic 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; } ////// implement the url in action controller to get the file //////the key id///public override String GetFileUrl(string uid) { return "/GridJs2/GetFile?id=" + uid; } }
6、創(chuàng)建一個名為GridJs2Controller.cs的新控制器并添加以下代碼。
/* 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(); 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('/', '.')); } ////// down load file //////[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); } }
7、在Startup.cs的Configure函數中插入如下代碼,設置License文件的路徑。
/* 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");
8、在Views/Home/index.cshtml 中插入以下代碼。
@{ ViewData["Title"] = "Home Page"; }
9、在Views/Home/文件夾下新建一個名為list.cshtml 的視圖,并插入以下代碼。
<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>
10、從GitHub下載xspread文件夾,放到wwwroot文件夾下,如下圖。
11、確保wwwroot/xspread/index.html中指定的端口號與項目的端口號相同。
12、構建應用程序并在您喜歡的瀏覽器中運行它。
以下是我們剛剛創(chuàng)建的 ASP.NET MVC 電子表格應用程序的演示。
如果你想試用Aspose的全部完整功能,可聯(lián)系在線客服獲取30天臨時授權體驗。
本站文章除注明轉載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn