3分钟学会在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格
在本文中,您将学习如何在ASP.NET MVC 应用程序中创建、读取和编辑 Excel 电子表格。为此,我们将创建一个由功能丰富的网格控件组成的电子表格应用程序,用于显示和编辑 Excel 文件,如下所示:
为了在 ASP.NET MVC 中创建电子表格应用程序,我们将使用Aspose.Cells.GridJs。API 允许您创建基于 Web 的应用程序以快速轻松地显示或编辑电子表格文档。此外,您可以导入流行的电子表格(XLS、XLSX、XLSM、XLSB、CSV、SpreadsheetML、ODS)文件格式()。此外,它还提供了强大而丰富的公式计算引擎,不仅可以计算内置函数,还可以计算自定义公式。
创建 ASP.NET MVC 电子表格应用程序的步骤
以下是在 ASP.NET MVC 中创建基于 Web 的电子表格应用程序的步骤。
1、在 Visual Studio 中创建一个新的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("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 });}}
4、在Models文件夹中新建一个名为TestConfig.cs 的类,并添加以下代码(根据您的环境更改文件夹路径)。
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文件夹中创建一个名为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、创建一个名为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 directoryFileInfo[] 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/UpdateCellpublic 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/Xspreadtmlpublic 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?idpublic 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、构建应用程序并在您喜欢的浏览器中运行它。
以下是我们刚刚创建的 ASP.NET MVC 电子表格应用程序的演示。
如果您有任何疑问或需求,请随时加入Aspose技术交流群(761297826),我们很高兴为您提供查询和咨询。
3分钟学会在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格相关推荐
- 在 ASP.NET MVC 中创建自定义 HtmlHelper
在ASP.NET MVC应用程序的开发中,我们常碰到类似Html.Label或Html.TextBox这样的代码,它将在网页上产生一个label或input标记.这些HtmlHelper的扩展方法有些 ...
- ASP.NET MVC中的身份验证
传统的登录验证方式,是通过将用户的登录状态信息保存在服务端的Session中,再利用客户端浏览器的Cookie保存SessionID,这样浏览器每次在向服务端发起请求时,都会携带该Cookie值,服务 ...
- 通过源代码研究ASP.NET MVC中的Controller和View(二)
通过源代码研究ASP.NET MVC中的Controller和View(一) 在开始之前,先来温习下上一篇文章中的结论(推论): IView是所有HTML视图的抽象 ActionResult是Cont ...
- 在Asp.Net MVC中实现RequiredIf标签对Model中的属性进行验证
在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现RequiredIf标签对Model中的属性进行验证 具体场景为:某一属性是否允许为null的验证,要根据另 ...
- ASP.NET MVC中你必须知道的13个扩展点
ScottGu在其最新的博文中推荐了Simone Chiaretta的文章13 ASP.NET MVC extensibility points you have to know,该文章为我 ...
- Asp.net mvc中的Ajax处理
在Asp.net MVC中的使用Ajax, 可以使用通用的Jquery提供的ajax方法,也可以使用MVC中的AjaxHelper. 这篇文章不对具体如何使用做详细说明,只对于在使用Ajax中的一些需 ...
- 在 ASP.NET MVC 中使用 Chart 控件
在 .NET 3.5 的时候,微软就提供了一个 Chart 控件,网络上有大量的关于在 VS2008 中使用这个控件的文章,在 VS2010 中,这个控件已经被集成到 ASP.NET 4.0 中,可以 ...
- 在ASP.NET MVC中使用IIS级别的URL Rewrite
在ASP.NET MVC中使用IIS级别的URL Rewrite 原文 在ASP.NET MVC中使用IIS级别的URL Rewrite 大约一年半前,我在博客上写过一系列关于URL Rewrite的 ...
- ASP.NET MVC中实现多个按钮提交的几种方法
有时候会遇到这种情况:在一个表单上需要多个按钮来完成不同的功能,比如一个简单的审批功能. 如果是用webform那不需要讨论,但asp.net mvc中一个表单只能提交到一个Action处理,相对比较 ...
最新文章
- 量子计算机理论基础,所谓量子计算机,是指建立在量子力学理论基础上的计算机...
- Unity教程:如何使用枚举来帮助简化游戏开发
- 使用rx-java的异步抽象
- opencv:畸变矫正:透视变换算法的思想与实现
- wince中的背光灯控制
- excel power bi 常用函数
- 树莓派舵机控制c语言,第8章 树莓派控制伺服电机(舵机)
- 图虫知识共享协议_100%避免图片版权侵权的方法(网站图片侵权赔款标准)
- 50内的勾股数java_学习知识:50以内勾股数有哪些
- 直播电商如何才能“酒香不怕巷子深”?
- 【学习随记】Ubuntu使用U盘相关问题
- 【踩坑】mirai登陆失败反复验证码或提示登录存在安全风险或提示版本过低的解决方法
- android 自定义相册选择,Android图片选择器,支持拍照、从相册选择、裁剪、自定义主题...
- 小米智能插排内部结构
- 专访 | 刘嘉松:开源,互惠且共赢
- 瞬时: lnstant
- [Pytorch系列-61]:循环神经网络 - 中文新闻文本分类详解-3-CNN网络训练与评估代码详解
- 独立开发者+开源项目,超级个体的价值模式
- 基于python的opencv_基于Python和OpenCV的人脸检测
- unity3d webplayer打开新窗口
热门文章
- 尚硅谷:jQuery的删除节点
- 项目踩坑之Echarts数据视图不更新问题
- MySQL数据库索引:删除、查看、创建索引
- 多因子策略中的IC、IR是什么,以及如何计算
- vmware 共享文件夹失效
- 在服务器网站上做跳转页面跳转页面,服务器怎么设置跳转页面跳转页面
- [日推荐]『小易充电』随时随地给电动车充电!
- AV1 概括性论文《An Overview of Core Coding Tools in the AV1 Video Codec》学习
- 巧用Macrodroid自动钉钉打卡
- vlookup 2张表 显示na_12个最新Vlookup函数示例大全,再不收藏就是你的错了!