.NET 帮助

Datatables .NET(开发者如何使用)

雷根·彭
雷根·彭
2024年一月14日
分享:

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

如何在 ASP.NET Web 应用程序中使用 DataTables?

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

  2. 添加 DataTables 客户端样式包

  3. 安装 Entity Framework 核心软件包,仅安装核心软件

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

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

  6. 设置配置

  7. 构建并运行程序

  8. 使用IronXL for Excel Data Export将数据导出到Excel文件中

什么是 DataTables.NET?

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

服务器端处理

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

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

在服务器端处理过程中,API 不发送整个数据集,而是以易于管理的分块形式传输数据,通常每页约有 50 条记录。 通过这样做,加载时间显著改善,因为 jQuery DataTables 现在加载的是一个适中的记录数(约 50),而不是一次处理整个数据集。 这种方法可以减少 CPU 和带宽的使用,在 API 和 DataTable 之间创建更高效的交互。

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

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

首先,我们需要将 DataTables.NET 客户端库添加到我们的项目中。 本文将使用基于.NET 8的ASP.NET Core Web应用程序(Razor Pages)项目。您可以根据需要使用任何Web应用程序项目。

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

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
$vbLabelText   $csharpLabel

添加 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
$vbLabelText   $csharpLabel

添加高级交互控件

我们将在 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>"; }
            },
        ]
    });
});
JAVASCRIPT

现在,我们需要添加一个 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
$vbLabelText   $csharpLabel

我们需要添加控制器。

添加产品控制器

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

[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
$vbLabelText   $csharpLabel

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

现在,我们需要设置数据库并在 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
$vbLabelText   $csharpLabel

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

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

Add-Migration init

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

Update-Database

上述命令将在我们的数据库中创建表格。 在产品表中添加虚拟数据,您可以从Mockaroo生成随机数据。

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

输出

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

DataTables.NET(它如何为开发者工作):图 2 - 输出

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

DataTables.NET(开发者如何使用):图 3 - 分页

输出用户界面

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

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

您可以通过点击探索DataTables.NET文档来了解更多内容。

IronXL 简介

IronXL - Excel Library for .NET 是一个库,可以让您在 .NET 应用程序中处理 Excel 文件。 它可以创建Excel电子表格读取CSV文件编辑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
$vbLabelText   $csharpLabel

我们以非常简单轻松的方式将列表创建为 Excel 文件。

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

IronXL提供全面的创建XLSX文件教程读取Excel的代码示例,以及API文档,以最佳方式使用其全面的API。

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

IronPDF 是一种解决方案,旨在将网页、URL 和 HTML 转换为 PDF 文档。 生成的PDF保留了源网页的原始格式和样式元素。 此工具在创建基于网页内容的 PDF 版本,如报告和发票方面特别有效。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

结论

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

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

雷根·彭
软件工程师
Regan毕业于雷丁大学,拥有电子工程学士学位。在加入Iron Software之前,他的前工作职位要求他专注于单一任务;他在Iron Software最喜欢的是能进行多种工作,无论是增加销售价值、技术支持、产品开发还是营销。他喜欢了解开发人员如何使用Iron Software的库,并利用这些知识不断改进文档和开发产品。
< 前一页
Sqlite C# .NET(开发者如何使用)
下一步 >
C# 空合并(开发人员如何使用)