Trong bài viết này, bạn sẽ học cách tạo, đọc và chỉnh sửa bảng tính Excel trong ứng dụng ASP.NET MVC. Đối với điều này, chúng tôi sẽ tạo một ứng dụng bảng tính bao gồm một điều khiển lưới giàu tính năng để hiển thị và chỉnh sửa các tệp Excel, như được hiển thị bên dưới.

.NET API để tạo ứng dụng bảng tính ASP.NET MVC

Để tạo ứng dụng bảng tính trong ASP.NET MVC, chúng ta sẽ sử dụng Aspose.Cells.GridJs. API cho phép bạn tạo các ứng dụng dựa trên web để hiển thị hoặc chỉnh sửa tài liệu bảng tính một cách nhanh chóng và dễ dàng. Hơn nữa, bạn có thể nhập các định dạng tệp bảng tính phổ biến (XLS, XLSX, XLSM, XLSB, CSV, SpreadsheetML, ODS) (đọc thêm). Ngoài ra, nó cung cấp một Công cụ tính toán công thức mạnh mẽ và phong phú để tính toán không chỉ các hàm tích hợp mà còn cả các công thức tùy chỉnh. Bạn có thể cài đặt Aspose.Cells.GridJs từ NuGet.

PM> Install-Package Aspose.Cells.GridJs

Các bước tạo ứng dụng bảng tính ASP.NET MVC

Sau đây là các bước để tạo ứng dụng bảng tính dựa trên web trong ASP.NET MVC.

  1. Tạo một ASP.NET Core Web App mới (Model-View-Controller) trong Visual Studio.
  1. Cài đặt Aspose.Cells.GridJs từ NuGet.
  1. Chèn mã sau vào 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 });
        }
    }
  1. Tạo một lớp mới có tên TestConfig.cs trong thư mục Models và thêm mã sau (thay đổi đường dẫn thư mục theo môi trường của bạn).
public class TestConfig
{
    ///<summary>
    /// thư mục chứa các tệp sổ làm việc
    ///</summary>
    internal static String ListDir = @"D:\tmpdel\storage\wb";
    ///<summary>
    /// temp thư mục để lưu trữ các tập tin
    ///</summary>
    internal static String TempDir = @"D:\tmpdel\storage\wb\tmp\";
}
  1. Tạo một lớp mới có tên LocalFileCache.cs trong thư mục Mô hình và thêm mã sau.
/* Add the following namespaces as well.
using Aspose.Cells.GridJs;
using System.IO;
*/

public class LocalFileCache : GridCacheForStream
{

    ///<summary>
    /// Thực hiện phương pháp này để savecache, lưu luồng vào đối tượng cache với key id.
    ///</summary>
    ///<param name="s"> dòng nguồn</param>
    ///<param name="uid"> anh ấy 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>
    /// Triển khai phương thức này để loadcache với key uid, trả về luồng từ đối tượng cache.
    ///</summary>
    ///<param name="uid"> mã khóa</param>
    ///<returns> luồng từ bộ nhớ 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>
    /// triển khai url trong bộ điều khiển hành động để lấy tệp
    ///</summary>
    ///<param name="uid"> mã khóa</param>
    ///<returns></returns>
    public override String GetFileUrl(string uid)
    {
        return "/GridJs2/GetFile?id=" + uid;
    }

}
  1. Tạo một bộ điều khiển mới có tên GridJs2Controller.cs và thêm mã sau.
/* 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 = Danh sách mới<object>();
        ArrayList dirlistsss = new ArrayList();
        ArrayList filelistsss = new ArrayList();

        DirectoryInfo dir = new DirectoryInfo(TestConfig.ListDir);

        //tìm các tập tin trong thư mục
        FileInfo[] fi = dir.GetFiles();
        foreach (FileInfo f in fi)
        {
            String fname = f.FullName.ToString();
            dirlistsss.Add(fname);
            filelistsss.Add(Path.GetFileName(fname));
        }
        //  Xem dữ liệu.
        ViewBag.dirlist = dirlistsss;
        ViewBag.filelist = filelistsss;
        return View("~/Views/Home/list.cshtml");
    }

    // NHẬN: / 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);
    }


    // NHẬN: / GridJs2 / Xspreadtml
    public ActionResult Xspreadtml(String filename)
    {
        return Redirect("~/xspread/index.html?file=" + filename);
    }

    // NHẬN: / GridJs2 / Hình ảnh? 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");
    }

    //nếu sử dụng GridCacheForStream bạn cần đặt api này
    // NHẬN: / 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";
    }




    // NHẬN: / 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>
    /// Tải tập tin
    ///</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);
    }


}
  1. Chèn đoạn mã sau vào chức năng Định cấu hình của Startup.cs và đặt đường dẫn của tệp giấy phép (nhận giấy phép miễn phí).
/* 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");
  1. Chèn mã sau vào Lượt xem / Trang chủ / index.cshtml.
@{
    ViewData["Title"] = "Home Page";
}
  1. Tạo một dạng xem mới có tên list.cshtml trong Chế độ xem / Trang chủ / thư mục và chèn mã sau.
<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>
  1. Tải xuống thư mục xspread từ GitHub và đặt nó trong thư mục wwwroot, như hình dưới đây.
  1. Đảm bảo rằng số cổng được chỉ định trong wwwroot / xspread / index.html giống với số cổng của dự án.

  2. Xây dựng ứng dụng và chạy nó trong trình duyệt yêu thích của bạn.

Demo - Tạo hoặc chỉnh sửa tệp Excel trong ASP.NET MVC

Sau đây là phần trình diễn ứng dụng bảng tính ASP.NET MVC mà chúng tôi vừa tạo.

Tải xuống mã nguồn

Bạn có thể tải xuống mã nguồn hoàn chỉnh của ứng dụng bảng tính từ GitHub.

Nhận giấy phép miễn phí

Bạn có thể sử dụng Aspose.Cells.GridJs mà không có giới hạn đánh giá bằng cách sử dụng giấy phép tạm thời.

Sự kết luận

Trong bài viết này, bạn đã học cách tạo ứng dụng bảng tính ASP.NET MVC với một loạt các tính năng để tạo và chỉnh sửa Excel và các tệp bảng tính khác. Bạn có thể tùy chỉnh ứng dụng này hoặc tích hợp nó vào ứng dụng web của riêng bạn. Trong trường hợp bạn có bất kỳ câu hỏi nào, vui lòng đăng lên diễn đàn của chúng tôi.

Xem thêm