במאמר זה, תלמד כיצד ליצור, לקרוא ולערוך גיליונות אלקטרוניים של Excel ביישום ASP.NET MVC. לשם כך, ניצור יישום גיליון אלקטרוני המורכב מבקרת רשת עשירה בתכונות לתצוגה ועריכה של קובצי Excel, כפי שמוצג להלן.

.NET API ליצירת יישום גיליון אלקטרוני של ASP.NET MVC

על מנת ליצור את אפליקציית הגיליון האלקטרוני ב-ASP.NET MVC, נשתמש ב-Aspose.Cells.GridJs. ה-API מאפשר לך ליצור יישומים מבוססי אינטרנט כדי להציג או לערוך מסמכי גיליון אלקטרוני במהירות ובקלות. יתר על כן, אתה יכול לייבא את פורמטי הקובץ הפופולריים של הגיליון האלקטרוני (XLS, XLSX, XLSM, XLSB, CSV, SpreadsheetML, ODS) (קרא עוד). בנוסף, הוא מספק מנוע חישוב פורמולה חזק ועשיר לחישוב לא רק את הפונקציות המובנות אלא גם נוסחאות מותאמות אישית. אתה יכול להתקין את Aspose.Cells.GridJs מ-NuGet.

PM> Install-Package Aspose.Cells.GridJs

שלבים ליצירת יישום גיליון אלקטרוני של ASP.NET MVC

להלן השלבים ליצירת יישום גיליון אלקטרוני מבוסס אינטרנט ב-ASP.NET MVC.

  1. צור אפליקציית ASP.NET Core Web חדשה (Model-View-Controller) ב-Visual Studio.
  1. התקן את Aspose.Cells.GridJs מ-NuGet.
  1. הכנס את הקוד הבא לתוך 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. צור מחלקה חדשה בשם TestConfig.cs בתיקייה Models והוסף את הקוד הבא (שנה את נתיבי התיקיה בהתאם לסביבה שלך).
public class TestConfig
{
    ///<summary>
    /// הספרייה המכילה קבצי חוברת עבודה
    ///</summary>
    internal static String ListDir = @"D:\tmpdel\storage\wb";
    ///<summary>
    /// ספריית זמני לאחסון קבצים
    ///</summary>
    internal static String TempDir = @"D:\tmpdel\storage\wb\tmp\";
}
  1. צור מחלקה חדשה בשם LocalFileCache.cs בתיקייה Models והוסף את הקוד הבא.
/* Add the following namespaces as well.
using Aspose.Cells.GridJs;
using System.IO;
*/

public class LocalFileCache : GridCacheForStream
{

    ///<summary>
    /// יישם שיטה זו כדי לשמור את המטמון, לשמור את הזרם לאובייקט המטמון עם מזהה המפתח.
    ///</summary>
    ///<param name="s"> זרם המקור</param>
    ///<param name="uid"> מזהה מפתח.</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;
    }

}
  1. צור בקר חדש בשם 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));
        }
        //  ViewData.
        ViewBag.dirlist = dirlistsss;
        ViewBag.filelist = filelistsss;
        return View("~/Views/Home/list.cshtml");
    }

    // קבל: /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]
    // פוסט: /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";
    }




    // 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('/', '.'));
    }


    ///<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);
    }


}
  1. הכנס את הקוד הבא בפונקציית Configure של Startup.cs והגדר את הנתיב של קובץ הרישיון (קבל רישיון בחינם).
/* 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. הכנס את הקוד הבא ב-Views/Home/index.cshtml.
@{
    ViewData["Title"] = "Home Page";
}
  1. צור תצוגה חדשה בשם list.cshtml תחת Views/Home/ תיקייה והכנס את הקוד הבא.
<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. הורד את התיקיה xspread מ-GitHub והצב אותה תחת תיקיית wwwroot, כפי שמוצג להלן.
  1. ודא שמספר היציאה שצוין ב-wwwroot/xspread/index.html זהה למספר היציאה של הפרויקט.

  2. בנה את האפליקציה והפעל אותה בדפדפן המועדף עליך.

הדגמה - צור או ערוך קבצי Excel ב-ASP.NET MVC

להלן ההדגמה של יישום הגיליון האלקטרוני ASP.NET MVC שיצרנו זה עתה.

הורד את קוד המקור

אתה יכול להוריד את קוד המקור המלא של אפליקציית הגיליון האלקטרוני מ-GitHub.

קבל רישיון חינם

אתה יכול להשתמש ב-Aspose.Cells.GridJs ללא מגבלות הערכה באמצעות רישיון זמני.

סיכום

במאמר זה, למדת כיצד ליצור יישום גיליון אלקטרוני של ASP.NET MVC עם מגוון תכונות ליצירה ועריכה של Excel וקובצי גיליונות אלקטרוניים אחרים. אתה יכול להתאים אישית את היישום הזה או לשלב אותו ביישום האינטרנט שלך. למקרה שיש לך שאלות כלשהן, אל תהסס לכתוב בפורום שלנו.

ראה גם