在本文中,您将学习如何在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 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、构建应用程序并在您喜欢的浏览器中运行它。
以下是我们刚刚创建的 ASP.NET MVC 电子表格应用程序的演示。
如果您有任何疑问或需求,请随时加入Aspose技术交流群(761297826),我们很高兴为您提供查询和咨询。