.NET 帮助

Datatables .NET(它是如何为开发人员工作的)

发布 2024年一月14日
分享:

ASP.NET 开发人员通常会寻求高效的方法来展示具有排序、搜索和分页等高级功能的表格数据或 HTML 表格。 数据表.NET 是一个功能强大的 jQuery、JavaScript 库和高度灵活的工具,可帮助在网络应用程序中创建交互式和功能丰富的表格。在本文中,我们将探讨如何将 DataTables.NET 分布文件(一种用于服务器端处理的表格增强库)集成到 ASP.NET 项目中,以增强表格数据的显示效果和用户体验。

如何在 ASP.NET 网络应用程序中使用数据表?

1.创建 ASP.NET 网络应用程序

2.添加 DataTables 客户端样式包

3.安装实体框架核心软件包,仅安装核心软件

4.添加模型类、控制器和 Razor 页面

5.在 JS 文件中添加 JavaScript 代码

6.设置配置

7.构建并运行程序

8.使用以下工具将数据导出到 Excel 文件 IronXL

什么是 Datatables.NET?

Datatables.NET是一个jQuery JavaScript库,允许您在.NET应用程序中创建CDN和操作交互式表格。它基于 jQuery DataTables 插件,该插件为动态和静态 HTML 表格提供了分页、排序、过滤和滚动等全面的 API 功能。它是一个可与各种数据源(如 SQL 数据库、AJAX 或内存对象)配合使用的表格增强库。

服务器端处理

考虑这样一种情况:您有一个提供大量产品数据集的 API 端点。标准方法包括 jQuery DataTables 对该 API 进行 AJAX 调用,获取 JSON 格式的产品列表,然后渲染 HTML 表格。这就是所谓的客户端处理,对于较小的数据集(通常为 100 到 1000 条记录)来说非常有效。但是,当数据集扩展到 10,000 条记录或更多时会发生什么情况呢?

在处理大量记录时,将整个数据集一次性发送到浏览器变得不切实际。一次性传输 10,000 条记录不仅浪费带宽,还会占用浏览器资源。在这种情况下,另一种方法(服务器端处理)对优化性能至关重要。

在服务器端处理过程中,应用程序接口不是发送整个数据集,而是以易于管理的分块方式传输数据,通常每页约有 50 条记录。通过这种方式,jQuery DataTables 的加载时间大大缩短,因为现在加载的记录数量并不多 (~50) 而不是一次性处理整个数据集。这种方法可以减少 CPU 和带宽的使用,在 API 和 DataTable 之间创建更高效的交互。

在本文中,我们将探讨在 ASP.NET Razor Page 应用程序中实现服务器端处理,演示如何有效地处理和显示大量数据集,同时提高网络应用程序的整体性能。

在 ASP.NET 8 中开始使用 Datatables.NET

要开始使用,我们需要在项目中添加 Datatables.NET 客户端库。本文将使用 ASP.NET Core Web App (剃刀页) 项目。您可以根据自己的要求使用任何 Web App 项目。

要添加客户端库,请右键单击 "解决方案">"添加">"客户端库",然后搜索数据表,如下图所示。

Datatables .NET(如何为开发人员工作):图 1 - 添加客户端库

现在,我们需要添加模型类、数据库上下文、控制器、HTML 表格和 AJAX 调用。

但在此之前,我们需要安装 EntityFramework Nuget 包,以便将应用程序与数据库连接起来。本文将使用 "代码优先 "方法,你也可以根据自己的偏好使用 "数据库优先 "方法。

安装以下本地托管软件包:

1.Microsoft.EntityFrameworkCore

2.Microsoft.EntityFrameworkCore.Design

3.Microsoft.EntityFrameworkCore.SqlServer

4.Microsoft.EntityFrameworkCore.Tools

使用 NuGet 软件包管理器控制台中的 install-package 命令安装上述软件包,或从 NuGet 软件包管理器解决方案中搜索安装。

添加模型类

我在本例中使用的是产品模型类,你可以根据自己的要求使用。

public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; } = string.Empty;
    public string ProductPrice { get; set; } = string.Empty;
    public string ProductWeight { get; set; } = string.Empty;
    public string ProductDescription { get; set; } = string.Empty;
    public DateTime ProductManufacturingDate { get; set; }
    public DateTime ProductExpiryDate { get; set; }
}
public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; } = string.Empty;
    public string ProductPrice { get; set; } = string.Empty;
    public string ProductWeight { get; set; } = string.Empty;
    public string ProductDescription { get; set; } = string.Empty;
    public DateTime ProductManufacturingDate { get; set; }
    public DateTime ProductExpiryDate { get; set; }
}
Public Class Product
	Public Property Id() As Integer
	Public Property ProductName() As String = String.Empty
	Public Property ProductPrice() As String = String.Empty
	Public Property ProductWeight() As String = String.Empty
	Public Property ProductDescription() As String = String.Empty
	Public Property ProductManufacturingDate() As DateTime
	Public Property ProductExpiryDate() As DateTime
End Class
VB   C#

添加 ApplicationDBContext 类

public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
    {
    }
    public DbSet<Product> Products { get; set; }
}
public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
    {
    }
    public DbSet<Product> Products { get; set; }
}
Public Class ApplicationDBContext
	Inherits DbContext

	Public Sub New(ByVal options As DbContextOptions(Of ApplicationDBContext))
		MyBase.New(options)
	End Sub
	Public Property Products() As DbSet(Of Product)
End Class
VB   C#

添加高级交互控制

我们将在 wwwroot>js 文件夹中添加 ProductDatatables.js,用于添加分页、搜索等高级控件。

//add advanced interaction controls
$(document).ready(function () {
    $("#productDatatable").DataTable({
        "processing": true,
        "serverSide": true,
        "filter": true,
        "ajax": {
            "url": "/api/Product",
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [{
            "targets": [0].data,
            "visible": false,
            "searchable": false
        }],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "productName", "name": "ProductName", "autoWidth": true },
            { "data": "productPrice", "name": "ProductPrice", "autoWidth": true },
            { "data": "productWeight", "name": "ProductWeight", "autoWidth": true },
            { "data": "productDescription", "name": "ProductDescription", "autoWidth": true },
            { "data": "productManufacturingDate", "name": "ProductManufacturingDate", "autoWidth": true },
            { "data": "productExpiryDate", "name": "ProductExpiryDate", "autoWidth": true },
            {
                "render": function (data, row) { return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" + row.id + "'); >Delete</a>"; }
            },
        ]
    });
});
//add advanced interaction controls
$(document).ready(function () {
    $("#productDatatable").DataTable({
        "processing": true,
        "serverSide": true,
        "filter": true,
        "ajax": {
            "url": "/api/Product",
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [{
            "targets": [0].data,
            "visible": false,
            "searchable": false
        }],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "productName", "name": "ProductName", "autoWidth": true },
            { "data": "productPrice", "name": "ProductPrice", "autoWidth": true },
            { "data": "productWeight", "name": "ProductWeight", "autoWidth": true },
            { "data": "productDescription", "name": "ProductDescription", "autoWidth": true },
            { "data": "productManufacturingDate", "name": "ProductManufacturingDate", "autoWidth": true },
            { "data": "productExpiryDate", "name": "ProductExpiryDate", "autoWidth": true },
            {
                "render": function (data, row) { return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" + row.id + "'); >Delete</a>"; }
            },
        ]
    });
});
'add advanced interaction controls
$(document).ready([function] () {
	$("#productDatatable").DataTable({
		"processing":= True, "serverSide":= True, "filter":= True, "ajax":= {
			"url":= "/api/Product",
			"type":= "POST",
			"datatype":= "json"
		},
		"columnDefs":= ({
			"targets":= (0).data,
			"visible":= False,
			"searchable":= False
		}), "columns":= ({
			"data":= "id",
			"name":= "Id",
			"autoWidth":= True
		},
		{
			"data":= "productName",
			"name":= "ProductName",
			"autoWidth":= True
		},
		{
			"data":= "productPrice",
			"name":= "ProductPrice",
			"autoWidth":= True
		},
		{
			"data":= "productWeight",
			"name":= "ProductWeight",
			"autoWidth":= True
		},
		{
			"data":= "productDescription",
			"name":= "ProductDescription",
			"autoWidth":= True
		},
		{
			"data":= "productManufacturingDate",
			"name":= "ProductManufacturingDate",
			"autoWidth":= True
		},
		{
			"data":= "productExpiryDate",
			"name":= "ProductExpiryDate",
			"autoWidth":= True
		},
		{
			"render":= [function] (data, row) { Return "<a href='#' class='btn btn-danger' onclick=DeleteProduct('" & row.id & "'); >Delete</a>"; }
		},
		)
}); })
VB   C#

现在,我们需要添加一个 HTML 表格。

添加 HTML 表格

在 index.cshtml 文件中编写以下代码,添加静态 HTML 页面。

//static HTML page
@page
@model IndexModel
@{
    ViewData ["Title"] = "Home page";
}
<link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<div class="container">
    <br />
    <div style="width:90%; margin:0 auto;">
        <table id="productDatatable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Product Name</th>
                    <th>Product Price</th>
                    <th>Product Weight</th>
                    <th>Product Description</th>
                    <th>Product Manufacturing Date</th>
                    <th>Product Expiry Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
        </table>
    </div>
</div>
@section Scripts
{
    <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
    <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script>
    <script src="~/js/ProductDatatable.js"></script>
}
//static HTML page
@page
@model IndexModel
@{
    ViewData ["Title"] = "Home page";
}
<link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<div class="container">
    <br />
    <div style="width:90%; margin:0 auto;">
        <table id="productDatatable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Product Name</th>
                    <th>Product Price</th>
                    <th>Product Weight</th>
                    <th>Product Description</th>
                    <th>Product Manufacturing Date</th>
                    <th>Product Expiry Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
        </table>
    </div>
</div>
@section Scripts
{
    <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
    <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script>
    <script src="~/js/ProductDatatable.js"></script>
}
'static HTML page
page model ReadOnly Property () As IndexModel
	ViewData ("Title") = "Home page"
End Property
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div class="container"> <br /> <div style="width:90%; margin:0 auto;"> <table id="productDatatable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0"> <thead> <tr> <th> Id</th> <th> Product Name</th> <th> Product Price</th> <th> Product Weight</th> <th> Product Description</th> <th> Product Manufacturing @Date</th> <th> Product Expiry @Date</th> <th> Actions</th> </tr> </thead> </table> </div> </div> @section Scripts
"100%" cellspacing="0"> (Of thead) (Of tr) (Of th) Id</th> (Of th) Product Name</th> (Of th) Product Price</th> (Of th) Product Weight</th> (Of th) Product Description</th> (Of th) Product Manufacturing [Date]</th> (Of th) Product Expiry [Date]</th> (Of th) Actions</th> </tr> </thead> </table> </div> </div> section Scripts
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class="container"> <br /> <div style="width:90%; margin:0 auto;"> <table id="productDatatable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing
"table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class="container"> <br /> <div style="width:90%; margin:0 auto;"> <table id="productDatatable" class="table table-striped table-bordered dt-responsive nowrap" width
"productDatatable" class="table table-striped table-bordered dt-responsive nowrap" width
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class="container"> <br /> <div style="width:90%; margin:0 auto;"> <table id="productDatatable" class
"width:90%; margin:0 auto;"> <table id="productDatatable" class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class="container"> <br /> <div style="width:90%; margin:0 auto;"> <table id
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
"container"> <br /> <div style="width:90%; margin:0 auto;"> <table id
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class="container"> <br /> <div style
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
"stylesheet" /> <div Class="container"> <br /> <div style
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class
"~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" /> <div Class
Private Private Private Private Private Private Private Friend <link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script> <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script> <script src="~/js/ProductDatatable.js"></script>
	"~/lib/datatables/js/dataTables.bootstrap4.min.js"></script> <script src="~/js/ProductDatatable.js"></script>
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script> <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script> <script src
	"~/lib/datatables/js/jquery.dataTables.min.js"></script> <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script> <script src
	Private Private Private <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script> <script src
End Class
VB   C#

我们需要添加控制器。

添加产品控制器

添加产品控制器,用于创建端点和直接拉取请求。

[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
    private readonly ApplicationDBContext context;
    public ProductController(ApplicationDBContext context)
    {
        this.context = context;
    }
    [HttpPost]
    public IActionResult GetProducts()
    {
        try
        {
            var draw = Request.Form ["draw"].FirstOrDefault();
            var start = Request.Form ["start"].FirstOrDefault();
            var length = Request.Form ["length"].FirstOrDefault();
            var searchValue = Request.Form ["search [value]"].FirstOrDefault();
            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;
            int recordsTotal = 0;
            var productData = context.Products.ToList();
            if (!string.IsNullOrEmpty(searchValue))
            {
                productData = productData.Where(m => m.ProductName.Contains(searchValue)

 m.ProductDescription.Contains(searchValue)

 m.Id.ToString().Contains(searchValue)).ToList();
            }
            recordsTotal = productData.Count();
            var data = productData.Skip(skip).Take(pageSize).ToList();
            var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
            return Ok(jsonData);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
    private readonly ApplicationDBContext context;
    public ProductController(ApplicationDBContext context)
    {
        this.context = context;
    }
    [HttpPost]
    public IActionResult GetProducts()
    {
        try
        {
            var draw = Request.Form ["draw"].FirstOrDefault();
            var start = Request.Form ["start"].FirstOrDefault();
            var length = Request.Form ["length"].FirstOrDefault();
            var searchValue = Request.Form ["search [value]"].FirstOrDefault();
            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;
            int recordsTotal = 0;
            var productData = context.Products.ToList();
            if (!string.IsNullOrEmpty(searchValue))
            {
                productData = productData.Where(m => m.ProductName.Contains(searchValue)

 m.ProductDescription.Contains(searchValue)

 m.Id.ToString().Contains(searchValue)).ToList();
            }
            recordsTotal = productData.Count();
            var data = productData.Skip(skip).Take(pageSize).ToList();
            var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
            return Ok(jsonData);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
<Route("api/[controller]")>
<ApiController>
Public Class ProductController
	Inherits ControllerBase

	Private ReadOnly context As ApplicationDBContext
	Public Sub New(ByVal context As ApplicationDBContext)
		Me.context = context
	End Sub
	<HttpPost>
	Public Function GetProducts() As IActionResult
		Try
			Dim draw = Request.Form ("draw").FirstOrDefault()
			Dim start = Request.Form ("start").FirstOrDefault()
			Dim length = Request.Form ("length").FirstOrDefault()
			Dim searchValue = Request.Form ("search [value]").FirstOrDefault()
			Dim pageSize As Integer = If(length IsNot Nothing, Convert.ToInt32(length), 0)
			Dim skip As Integer = If(start IsNot Nothing, Convert.ToInt32(start), 0)
			Dim recordsTotal As Integer = 0
			Dim productData = context.Products.ToList()
			If Not String.IsNullOrEmpty(searchValue) Then
				productData = productData.Where(Function(m) m.ProductName.Contains(searchValue) m.ProductDescription.Contains(searchValue) m.Id.ToString().Contains(searchValue)).ToList()
			End If
			recordsTotal = productData.Count()
			Dim data = productData.Skip(skip).Take(pageSize).ToList()
			Dim jsonData = New With {
				Key .draw = draw,
				Key .recordsFiltered = recordsTotal,
				Key .recordsTotal = recordsTotal,
				Key .data = data
			}
			Return Ok(jsonData)
		Catch ex As Exception
			Throw
		End Try
	End Function
End Class
VB   C#

在这里,我们在服务器端实现了分页和搜索功能。

现在,我们需要设置数据库并在 Program.cs 类中添加配置。如果您使用的是 .NET 5 或更低版本,可能需要在 Startup.cs 类中完成。

首先,在 appsettings.json 文件中添加以下连接字符串。

"ConnectionStrings": {
   "ProductDB": "Server=localserver\\SQLEXPRESS;Database=ProductDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;"
 },

现在,在 Program.cs 类中添加以下代码。

public static void Main(string [] args)
 {
     var builder = WebApplication.CreateBuilder(args);
     builder.Services.AddDbContext<ApplicationDBContext>(options =>
     {
         options.UseSqlServer(builder.Configuration.GetConnectionString("ProductDB"));
     });
     builder.Services.AddControllers();
     // Add services to the container.
     builder.Services.AddRazorPages();
     var app = builder.Build();
     // Configure the HTTP request pipeline.
     if (!app.Environment.IsDevelopment())
     {
         app.UseExceptionHandler("/Error");
         // The default HSTS value is 30 days. You may want to change this for production scenarios, see .NET documentation https://aka.ms/aspnetcore-hsts.
         app.UseHsts();
     }
     app.UseHttpsRedirection();
     app.UseStaticFiles();
     app.UseRouting();
     app.UseAuthorization();
     app.MapControllers();
     app.MapRazorPages();
     app.Run();
 }
public static void Main(string [] args)
 {
     var builder = WebApplication.CreateBuilder(args);
     builder.Services.AddDbContext<ApplicationDBContext>(options =>
     {
         options.UseSqlServer(builder.Configuration.GetConnectionString("ProductDB"));
     });
     builder.Services.AddControllers();
     // Add services to the container.
     builder.Services.AddRazorPages();
     var app = builder.Build();
     // Configure the HTTP request pipeline.
     if (!app.Environment.IsDevelopment())
     {
         app.UseExceptionHandler("/Error");
         // The default HSTS value is 30 days. You may want to change this for production scenarios, see .NET documentation https://aka.ms/aspnetcore-hsts.
         app.UseHsts();
     }
     app.UseHttpsRedirection();
     app.UseStaticFiles();
     app.UseRouting();
     app.UseAuthorization();
     app.MapControllers();
     app.MapRazorPages();
     app.Run();
 }
Public Shared Sub Main(ByVal args() As String)
	 Dim builder = WebApplication.CreateBuilder(args)
	 builder.Services.AddDbContext(Of ApplicationDBContext)(Sub(options)
		 options.UseSqlServer(builder.Configuration.GetConnectionString("ProductDB"))
	 End Sub)
	 builder.Services.AddControllers()
	 ' Add services to the container.
	 builder.Services.AddRazorPages()
	 Dim app = builder.Build()
	 ' Configure the HTTP request pipeline.
	 If Not app.Environment.IsDevelopment() Then
		 app.UseExceptionHandler("/Error")
		 ' The default HSTS value is 30 days. You may want to change this for production scenarios, see .NET documentation https://aka.ms/aspnetcore-hsts.
		 app.UseHsts()
	 End If
	 app.UseHttpsRedirection()
	 app.UseStaticFiles()
	 app.UseRouting()
	 app.UseAuthorization()
	 app.MapControllers()
	 app.MapRazorPages()
	 app.Run()
End Sub
VB   C#

我们需要运行迁移,因为我们采用的是代码优先的方法。

在软件包管理器控制台运行以下命令。

Add-Migration init

上述命令将创建迁移。现在,我们需要将这些迁移应用到数据库中。在软件包管理器控制台中运行以下命令。

Update-Database

上述命令将在数据库中创建表格。在产品表中添加虚拟数据,您可以从 莫卡鲁.

现在,构建并运行此应用程序。

输出

我们可以看到,我们有一个交互性很强的用户界面,带有高级交互控件。

Datatables .NET(如何为开发人员工作):图 2 - 输出

现在,分页在服务器端实现,如下图所示。

Datatables .NET(如何为开发人员工作):图 3 - 分页

输出用户界面

然后,数据将通过丰富的用户界面控件呈现在客户端。

Datatables .NET(如何为开发人员工作):图 4 - 用户界面

您可以从 DataTables.NET 文档中了解更多信息,请点击 这里.

介绍 IronXL

IronXL 是一个允许您在.NET 应用程序中处理 Excel 文件的库。它可以 创建, 读取, 编辑节省 各种格式的 Excel 文档,如 XLS、XLSX、CSV 和 TSV。它不需要安装 Microsoft Office 或 Excel Interop。它支持 .NET 8、7、6、5、Core、Framework 和 Azure。

我们经常需要将数据导出为 Excel 或 CSV 文件。在这种情况下,IronXL 是最佳选择。现在,我们将编写一段代码,将数据导出到 Excel 文件中。

安装 IronXL

在软件包管理器控制台输入以下命令,在我们的项目中安装 IronXL 库。

Install-Package ironXL.Excel

这将在我们的项目中安装 IronXL 和所需的依赖项。

将数据导出到 Excel

让我们编写一段代码,将产品列表转换成 Excel 文件。

public void ExportToExcel(List<Product> productList)
   {
       WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
       WorkSheet ws = wb.DefaultWorkSheet;
       int rowCount = 1;
       foreach (Product product in productList)
       {
           ws ["A" + (rowCount)].Value = product.Id.ToString();
           ws ["B" + (rowCount)].Value = product.ProductName;
           ws ["C" + (rowCount)].Value = product.ProductDescription;
           ws ["D" + (rowCount)].Value = product.ProductPrice;
           ws ["E" + (rowCount)].Value = product.ProductWeight;
           ws ["F" + (rowCount)].Value = product.ProductManufacturingDate;
           ws ["G" + (rowCount)].Value = product.ProductExpiryDate;
           rowCount++;
       }
       wb.SaveAs("product.xlsx");
   }
public void ExportToExcel(List<Product> productList)
   {
       WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
       WorkSheet ws = wb.DefaultWorkSheet;
       int rowCount = 1;
       foreach (Product product in productList)
       {
           ws ["A" + (rowCount)].Value = product.Id.ToString();
           ws ["B" + (rowCount)].Value = product.ProductName;
           ws ["C" + (rowCount)].Value = product.ProductDescription;
           ws ["D" + (rowCount)].Value = product.ProductPrice;
           ws ["E" + (rowCount)].Value = product.ProductWeight;
           ws ["F" + (rowCount)].Value = product.ProductManufacturingDate;
           ws ["G" + (rowCount)].Value = product.ProductExpiryDate;
           rowCount++;
       }
       wb.SaveAs("product.xlsx");
   }
Public Sub ExportToExcel(ByVal productList As List(Of Product))
	   Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
	   Dim ws As WorkSheet = wb.DefaultWorkSheet
	   Dim rowCount As Integer = 1
	   For Each product As Product In productList
		   ws ("A" & (rowCount)).Value = product.Id.ToString()
		   ws ("B" & (rowCount)).Value = product.ProductName
		   ws ("C" & (rowCount)).Value = product.ProductDescription
		   ws ("D" & (rowCount)).Value = product.ProductPrice
		   ws ("E" & (rowCount)).Value = product.ProductWeight
		   ws ("F" & (rowCount)).Value = product.ProductManufacturingDate
		   ws ("G" & (rowCount)).Value = product.ProductExpiryDate
		   rowCount += 1
	   Next product
	   wb.SaveAs("product.xlsx")
End Sub
VB   C#

我们用非常简单方便的方法将列表创建成 Excel 文件。

Datatables .NET(如何为开发人员工作):图 5 - Excel 输出

IronXL 提供全面的 教程, 代码示例文献资料 以最佳方式使用其全面的应用程序接口。

在优化 ASP.NET 性能方面,我们完全依赖于 Only Core Software,以确保精简高效的开发环境。利用 DataTables.NET 作为本地托管包,可进一步提高响应速度,最大限度地减少外部依赖性,从而简化数据处理和 Excel 导出。此外,在这个优化的、自成一体的生态系统中,代码贡献变得高效无缝。

结论

总之,在 ASP.NET 分发仓库项目中利用 DataTables.NET 进行服务器端处理被证明是有效处理大量数据集的良好策略。这种方法通过以可管理的数据块传输数据、减少带宽使用和增强用户体验来确保优化性能。IronXL 的集成进一步扩展了应用程序的功能,可轻松将表格数据导出到 Excel,以便进行全面的数据分析和报告。

通过采用这些技术,开发人员可以创建在丰富的交互性和资源效率之间取得平衡的网络应用程序,为用户提供无缝的响应式体验,尤其是在涉及大型数据集的情况下。IronXL 提供多种 授权取决于开发人员、项目和再分发需求的数量。许可证是永久性的,包括免费支持和更新。

< 前一页
Sqlite C# .NET(开发者如何使用)
下一步 >
C# 空合并运算符(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >