在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
ASP.NET 開發人員經常尋求有效的方法來呈現具有排序、搜索和分頁等高級功能的表格數據或 HTML 表格。 DataTables.NET 是一個強大的 jQuery、JavaScript 庫,以及高度靈活的工具,有助於在網頁應用程式中建立互動且功能豐富的表格。在本文中,我們將探討如何將 DataTables.NET 的分發檔案(一種伺服器端處理的表格增強庫)集成到 ASP.NET 專案中,以增強表格數據的呈現和使用者體驗。
建立 ASP.NET Web 應用程式
添加 DataTables 客戶端樣式包
安裝 Entity Framework Core 套件,僅限核心軟體
添加模型類別、控制器和 Razor 頁面
在 JS 文件中添加 JavaScript 代碼
設定配置
構建並運行程式
Datatables.NET 是一個 jQuery JavaScript 函式庫,允許你在 .NET 應用程式中創建 CDN 並操作互動式表格。它基於 jQuery DataTables 插件,提供全面的 API 功能,如分頁、排序、過濾和滾動,用於動態和靜態 HTML 表格。這是一個可以處理各種數據來源(如 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應用程序中實現服務端處理,演示如何有效地處理和顯示大量數據集,同時提升您的Web應用程序的整體性能。
要開始,我們需要在項目中添加 Datatables.NET 客戶端庫。本文將使用 ASP.NET Core Web 應用程式 (Razor Pages) 使用 .NET 8 的專案。您可以根據需求使用任何 Web 應用程式專案。
要新增用戶端程式庫,右鍵點擊解決方案 > 新增 > 用戶端程式庫,然後搜索資料表,如下所示。
現在,我們需要添加模型類、DB上下文、控制器、HTML表格和AJAX調用。
但在此之前,我們需要安裝EntityFramework Nuget套件以將應用程序與數據庫連接。本文將使用Code First方法,你可以根據你的偏好使用Database First方法。
安裝下列本地托管的包:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
使用NuGet套件管理器控制台中的install-package命令安裝上述包,或者通過在NuGet套件管理器解決方案中搜索來安裝它。
我是使用 Product 模型類別來做此範例,您可以根據您的需求使用。
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
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
我們將在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>"; }
},
)
}); })
現在,我們需要添加一個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
我們需要新增控制器。
新增產品控制器以建立端點並直接拉取請求。
[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
在這裡,我們已在伺服器端實現了分頁和搜尋功能。
現在,我們需要設置我們的資料庫,並在 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
我們需要執行遷移,因為我們正在使用代碼優先的方法。
在套件管理器控制台中執行以下命令。
Add-Migration init
上述指令將會建立一個遷移。現在我們需要將這些遷移應用到我們的資料庫中。在套件管理器控制台中執行以下指令。
Update-Database
上述命令將在我們的資料庫中創建表格。在Product表中添加虛擬資料,您可以從 Mockaroo現在,構建並運行此應用程式。
我們可以看到,我們有一個非常互動的UI,具有先進的交互控制。
現在,分頁在伺服器端如下面所示實現。
然後數據在客戶端使用豐富的介面控制進行渲染。
您可以通過點擊來探索更多有關DataTables.NET文件的內容 這裡.
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 函式庫,請在封裝管理員主控台中輸入以下指令。
Install-Package ironXL.Excel
這將在我們的專案中安裝 IronXL 和所需的依賴項。
讓我們編寫一個代碼將我們的產品列表轉換為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
我們已經以非常簡單和容易的方式從清單中創建了一個 Excel 文件。
IronXL 提供全面的 教程, 程式碼範例,和 文檔 以最佳方式使用其全面的 API。
在優化 ASP.NET 績效方面,我們僅依賴 Only Core Software,確保精簡和高效的開發環境。利用作為本地託管套件的 DataTables.NET 進一步提高了響應能力,最小化了外部依賴以簡化數據處理和 Excel 導出。此外,在這個優化且自包含的生態系統中,高效貢獻代碼變得更加輕鬆。
總結來說,在ASP.NET分發庫專案中利用DataTables.NET進行伺服端處理是一個有效處理大量數據的好策略。這種方法通過以可管理的塊狀傳輸數據來確保最佳性能,減少帶寬使用並提升用戶體驗。整合IronXL進一步擴展了應用的能力,使得將表格數據輕鬆導出到Excel進行全面數據分析和報告成為可能。
通過採用這些技術,開發人員可以創建在豐富的互動性和資源效率之間取得平衡的Web應用,為用戶提供無縫且響應迅速的體驗,尤其是在涉及大量數據集的情況下。IronXL提供了多種功能。 授權根據開發人員的數量、項目和重新分佈的需求。這些許可證是永久性的,並包括免費支持和更新。