在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
ASP.NET 開發人員經常尋求有效的方法來展示具有排序、搜尋和分頁等進階功能的表格數據或 HTML 表格。 DataTables.NET是一個強大的 jQuery 和 JavaScript 庫,以及高度靈活的工具,有助於在網絡應用程式中創建互動性強且功能豐富的表格。 在本文中,我們將探討如何將DataTables.NET分發檔案(用於伺服器端處理的表格增強庫)整合到ASP.NET專案中,以提升表格數據的呈現和用戶體驗。
建立 ASP.NET 網頁應用程式
添加 DataTables 客戶端樣式包
安裝 Entity Framework Core 套件,僅限核心軟體
添加模型類別、控制器和Razor頁面
在 JS 文件中添加 JavaScript 代碼
設置配置
構建並運行程式
DataTables.NET 是一個 jQuery JavaScript 庫,允許您在 .NET 應用程式中創建和操作互動式表格。 它基於 jQuery DataTables 插件,提供全面的 API 功能,例如分頁、排序、過濾和滾動,適用於動態和靜態的 HTML 表格。 這是一個增強表格的庫,可以與多種數據來源協同工作,如 SQL 數據庫、AJAX 或內存對象。
假設有一個情境,您有一個 API 端點正在傳送大量產品數據集。 標準方法涉及 jQuery DataTables 發出 AJAX 請求到此 API,取得 JSON 格式的產品列表,並渲染成 HTML 表格。 這被稱為客戶端處理,它對於較小的數據集效率很高,通常範圍在100到1000條記錄之間。 但是,當資料集擴展到10,000筆記錄或更多時會怎樣呢?
在處理大量記錄時,一次性將整個數據集傳送到瀏覽器變得不切實際。 一次傳輸 10,000 條記錄不僅浪費帶寬,還會對瀏覽器資源造成負擔。 在這種情況下,一種替代方法,伺服器端處理,成為優化性能的關鍵。
在伺服器端處理中,API 不會傳送整個數據集,而是將數據以可管理的塊形式傳輸,通常分頁並每頁約 50 條記錄。 透過這樣做,載入時間顯著改善,因為 jQuery DataTables 現在載入少量的記錄。(~50)而不是一次處理整個資料集。 這種方法減少了 CPU 和帶寬使用,使 API 和 DataTable 之間的互動更加高效。
在本文中,我們將探討在 ASP.NET Razor Page 應用程式中實現伺服器端處理,示範如何有效處理和顯示大量資料集,同時提升您的網頁應用程式的整體性能。
首先,我們需要將 DataTables.NET 用戶端庫添加到我們的專案中。 本文將使用 ASP.NET Core Web App(Razor Pages)使用 .NET 8 進行專案。您可以根據需求使用任何 Web 應用程式專案。
若要新增用戶端程式庫,請右鍵點選解決方案 > 新增 > 用戶端程式庫,並按如下圖所示搜尋資料表。
現在,我們需要添加模型類、數據庫上下文、控制器、HTML 表格和 AJAX 調用。
但是在此之前,我們需要安裝 EntityFramework NuGet 套件以將我們的應用程式連接到資料庫。 本文將使用 Code First 方法,您可以根據自己的喜好使用 Database First 方法。
安裝以下本地託管的套件:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
使用 NuGet 套件管理器控制台中的 install-package 命令安裝上述套件,或透過在 NuGet 套件管理器解決方案中搜尋來安裝它。
在此範例中,我使用了 Product Model Class,您可以根據需要使用。
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
我們會將 ProductDatatables.js 添加到 wwwroot>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
上述命令將在我們的數據庫中創建表格。 在產品表中添加虛擬數據,您可以從Mockaroo.
現在,構建並運行此應用程式。
我們可以看到,我們擁有一個非常互動的用戶界面,並配備了先進的互動控制項。
現在,分頁功能在伺服器端實現,如下所示。
然後在客戶端使用豐富的 UI 控制來呈現數據。
您可以點擊進入 DataTables.NET 文件以獲取更多資訊查看 DataTables.NET 文件資料.
IronXL - .NET 的 Excel 庫是一個庫,允許在 .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 函式庫安裝到我們的專案中。
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 提供全面的創建 XLSX 文件的教程, 讀取 Excel 的程式碼範例,和API 文件以最佳方式使用其全面的 API。
在優化 ASP.NET 性能時,我們專門依賴 Only Core Software,確保開發環境精簡且高效。 利用本地托管的 DataTables.NET 套件進一步提高響應速度,將外部依賴性降到最低,以實現精簡的數據處理和 Excel 導出。 此外,在這個優化且自我封閉的生態系統中,高效地貢獻程式碼變得十分流暢。
IronPDF 是一個專為轉換網頁、網址而設計的解決方案,將 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
總之,在 ASP.NET 分發庫專案中利用 DataTables.NET 進行伺服器端處理,被證明為有效處理大量數據集的良好策略。 此方法透過將數據分成可管理的區塊來傳輸,確保最佳效能,減少頻寬使用,並提升使用者體驗。 集成IronXL進一步擴展了應用程序的功能,使得表格數據輕鬆導出至Excel,用於綜合數據分析和報告。
透過採用這些技術,開發者可以創建在豐富的互動性與資源效率之間取得平衡的網頁應用程式,為用戶提供流暢且響應迅速的體驗,特別是在涉及大型數據集的情境中。 IronXL 提供各種IronXL 的授權選項,根據開發人員的數量、專案以及重新分配的需求而定。 許可證是永久的,並包括免費的支持和更新。