在本文中,您將學習如何在 ASP.NET MVC 應用程序中創建、讀取和編輯 Excel 電子表格。為此,我們將創建一個包含功能豐富的網格控件的電子表格應用程序來顯示和編輯 Excel 文件,如下所示。
![](images/ASP.NET-UI.jpg#center)
用於創建 ASP.NET MVC 電子表格應用程序的 .NET API
為了在 ASP.NET MVC 中創建電子表格應用程序,我們將使用 Aspose.Cells.GridJs。 API 允許您創建基於 Web 的應用程序以快速輕鬆地顯示或編輯電子表格文檔。此外,您可以導入流行的電子表格(XLS、XLSX、XLSM、XLSB、CSV、SpreadsheetML、ODS)文件格式(閱讀更多)。此外,它提供了強大而豐富的公式計算引擎,不僅可以計算內置函數,還可以計算自定義公式。您可以從 NuGet 安裝 Aspose.Cells.GridJs。
PM> Install-Package Aspose.Cells.GridJs
創建 ASP.NET MVC 電子表格應用程序的步驟
以下是在 ASP.NET MVC 中創建基於 Web 的電子表格應用程序的步驟。
- 在 Visual Studio 中創建一個新的 ASP.NET Core Web 應用程序(模型-視圖-控制器)。
![](images/Create-Project.jpg#center)
- 從 NuGet 安裝 Aspose.Cells.GridJs。
![](images/Install-AsposeCells_GridJs.jpg#center)
- 將以下代碼插入 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 });
}
}
- 在 Models 文件夾中創建一個名為 TestConfig.cs 的新類並添加以下代碼(根據您的環境更改文件夾路徑)。
public class TestConfig
{
///<summary>
/// 包含工作簿文件的目錄
///</summary>
internal static String ListDir = @"D:\tmpdel\storage\wb";
///<summary>
///temp 存放文件的目錄
///</summary>
internal static String TempDir = @"D:\tmpdel\storage\wb\tmp\";
}
- 在 Models 文件夾中創建一個名為 LocalFileCache.cs 的新類並添加以下代碼。
/* Add the following namespaces as well.
using Aspose.Cells.GridJs;
using System.IO;
*/
public class LocalFileCache : GridCacheForStream
{
///<summary>
///實現這個方法來savecache,將流保存到緩存對像中,並帶有key id。
///</summary>
///<param name="s">源流</param>
///<param name="uid">他的關鍵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>
/// 實現此方法以使用鍵 uid 加載緩存,從緩存對象返回流。
///</summary>
///<param name="uid">鑰匙編號</param>
///<returns>來自緩存的流</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>
/// 在動作控制器中實現 url 以獲取文件
///</summary>
///<param name="uid">鑰匙編號</param>
///<returns></returns>
public override String GetFileUrl(string uid)
{
return "/GridJs2/GetFile?id=" + uid;
}
}
- 創建一個名為 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 = 新列表<object>();
ArrayList dirlistsss = new ArrayList();
ArrayList filelistsss = new ArrayList();
DirectoryInfo dir = new DirectoryInfo(TestConfig.ListDir);
//查找目錄下的文件
FileInfo[] fi = dir.GetFiles();
foreach (FileInfo f in fi)
{
String fname = f.FullName.ToString();
dirlistsss.Add(fname);
filelistsss.Add(Path.GetFileName(fname));
}
// 查看數據。
ViewBag.dirlist = dirlistsss;
ViewBag.filelist = filelistsss;
return View("~/Views/Home/list.cshtml");
}
// 獲取:/GridJs2/DetailJson?文件名=
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 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]
// 帖子:/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);
}
// 獲取:/GridJs2/Xspreadtml
public ActionResult Xspreadtml(String filename)
{
return Redirect("~/xspread/index.html?file=" + filename);
}
// 獲取:/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");
}
//如果使用 GridCacheForStream 你需要設置這個 api
// 獲取:/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";
}
// 獲取:/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>
/// 下載文件
///</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);
}
}
- 在 Startup.cs 的 Configure 函數中插入以下代碼並設置許可證文件的路徑(免費獲得許可證)。
/* 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");
- 在 Views/Home/index.cshtml 中插入以下代碼。
@{
ViewData["Title"] = "Home Page";
}
- 在 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文件夾下,如下圖。
![](images/Import-GridJs-Folder.jpg#center)
11.確保wwwroot/xspread/index.html中指定的端口號與項目的端口號相同。
- 構建應用程序並在您喜歡的瀏覽器中運行它。
演示 - 在 ASP.NET MVC 中創建或編輯 Excel 文件
下面是我們剛剛創建的 ASP.NET MVC 電子表格應用程序的演示。
![](images/GridJsDemo.gif#center)
下載源代碼
您可以從 GitHub 下載電子表格應用程序的完整源代碼。
獲得免費許可證
你可以使用 Aspose.Cells.GridJs,沒有評估限制,使用臨時許可證。
結論
在本文中,您了解瞭如何創建具有一系列功能的 ASP.NET MVC 電子表格應用程序來創建和編輯 Excel 及其他電子表格文件。您可以自定義此應用程序或將其集成到您自己的 Web 應用程序中。如果您有任何疑問,請隨時發帖到我們的論壇。