IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发测试 -> 3分钟学会在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格 -> 正文阅读

[开发测试]3分钟学会在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格

在本文中,您将学习如何在ASP.NET MVC 应用程序中创建、读取和编辑 Excel 电子表格。为此,我们将创建一个由功能丰富的网格控件组成的电子表格应用程序,用于显示和编辑 Excel 文件,如下所示:

如何在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格?Aspose轻松搞定

为了在 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 应用程序(模型-视图-控制器)。

如何在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格?Aspose轻松搞定

2、从 NuGet安装Aspose.Cells.GridJs。

如何在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格?Aspose轻松搞定

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文件夹下,如下图。

如何在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格?Aspose轻松搞定

11、确保wwwroot/xspread/index.html中指定的端口号与项目的端口号相同。

12、构建应用程序并在您喜欢的浏览器中运行它。

以下是我们刚刚创建的 ASP.NET MVC 电子表格应用程序的演示。

如何在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格?Aspose轻松搞定


如果您有任何疑问或需求,请随时加入Aspose技术交流群(761297826),我们很高兴为您提供查询和咨询。

  开发测试 最新文章
pytest系列——allure之生成测试报告(Wind
某大厂软件测试岗一面笔试题+二面问答题面试
iperf 学习笔记
关于Python中使用selenium八大定位方法
【软件测试】为什么提升不了?8年测试总结再
软件测试复习
PHP笔记-Smarty模板引擎的使用
C++Test使用入门
【Java】单元测试
Net core 3.x 获取客户端地址
上一篇文章      下一篇文章      查看所有文章
加:2021-09-01 12:14:13  更:2021-09-01 12:16:15 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/14 19:11:57-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码